新增 文件操作 删除撤回功能
This commit is contained in:
1 parent
395b469d96
commit
740d0d28a2
16 files changed
+1812
-41
No files matched your search
@@ -67,6 +67,27 @@ class LibraryDatabase {
|
||||
// 列已存在,忽略错误
|
||||
}
|
||||
|
||||
// 添加 rating 列(如果不存在)
|
||||
try {
|
||||
this.db.exec(`ALTER TABLE images ADD COLUMN rating INTEGER DEFAULT 0`);
|
||||
} catch (e) {
|
||||
// 列已存在,忽略错误
|
||||
}
|
||||
|
||||
// 添加 favorite 列(如果不存在)
|
||||
try {
|
||||
this.db.exec(`ALTER TABLE images ADD COLUMN favorite INTEGER DEFAULT 0`);
|
||||
} catch (e) {
|
||||
// 列已存在,忽略错误
|
||||
}
|
||||
|
||||
// 添加 tags 列(如果不存在)
|
||||
try {
|
||||
this.db.exec(`ALTER TABLE images ADD COLUMN tags TEXT DEFAULT ''`);
|
||||
} catch (e) {
|
||||
// 列已存在,忽略错误
|
||||
}
|
||||
|
||||
// Folders table
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS folders (
|
||||
@@ -89,6 +110,9 @@ class LibraryDatabase {
|
||||
CREATE INDEX IF NOT EXISTS idx_folder_parent ON folders(parent_path);
|
||||
-- 复合索引:优化文件夹+时间排序查询
|
||||
CREATE INDEX IF NOT EXISTS idx_folder_created ON images(folder, created_at DESC);
|
||||
-- 评分和收藏索引:优化筛选查询
|
||||
CREATE INDEX IF NOT EXISTS idx_rating ON images(rating DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_favorite ON images(favorite DESC);
|
||||
`);
|
||||
|
||||
// Metadata table for tracking database modifications
|
||||
@@ -171,6 +195,12 @@ class LibraryDatabase {
|
||||
return stmt.get(imagePath);
|
||||
}
|
||||
|
||||
getImagesByFolderPrefix(folderPath) {
|
||||
// 获取文件夹内所有图片记录(包括子文件夹)
|
||||
const stmt = this.db.prepare('SELECT * FROM images WHERE folder = ? OR folder LIKE ?');
|
||||
return stmt.all(folderPath, `${folderPath}/%`);
|
||||
}
|
||||
|
||||
getAllImages() {
|
||||
// ⚠️ 警告:此方法会加载所有图片到内存,仅用于调试!
|
||||
// 生产环境请使用 searchImages() 或流式查询
|
||||
|
||||
@@ -16,7 +16,8 @@
|
||||
"glob": "^10.3.10",
|
||||
"p-limit": "^7.2.0",
|
||||
"sharp": "^0.33.0",
|
||||
"socket.io": "^4.6.0"
|
||||
"socket.io": "^4.6.0",
|
||||
"trash": "^8.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"cross-env": "^7.0.3",
|
||||
|
||||
@@ -118,6 +118,23 @@ server.listen(PORT, () => {
|
||||
try {
|
||||
const currentConfig = config.loadConfig();
|
||||
|
||||
// 启动定时清理任务(每分钟检查一次过期临时文件)
|
||||
const fileService = app.get('fileService');
|
||||
setInterval(async () => {
|
||||
if (currentConfig.libraries && currentConfig.libraries.length > 0) {
|
||||
for (const library of currentConfig.libraries) {
|
||||
try {
|
||||
const result = await fileService.cleanExpiredTempFiles(library.id);
|
||||
if (result.cleaned > 0) {
|
||||
console.log(`🧹 清理了 ${result.cleaned} 个过期临时文件`);
|
||||
}
|
||||
} catch (error) {
|
||||
// 忽略错误
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 60 * 1000); // 每分钟执行一次
|
||||
|
||||
// 恢复所有素材库的扫描状态
|
||||
if (currentConfig.libraries && currentConfig.libraries.length > 0) {
|
||||
scanManager.restoreAllStates(currentConfig.libraries);
|
||||
|
||||
@@ -12,6 +12,7 @@ const { errorHandler } = require('./middleware/errorHandler');
|
||||
const LibraryService = require('./services/LibraryService');
|
||||
const ImageService = require('./services/ImageService');
|
||||
const ScanService = require('./services/ScanService');
|
||||
const FileService = require('./services/FileService');
|
||||
|
||||
/**
|
||||
* 创建 Express 应用
|
||||
@@ -54,19 +55,24 @@ function createApp(dependencies) {
|
||||
io
|
||||
);
|
||||
|
||||
const fileService = new FileService(dbPool, configManager);
|
||||
|
||||
// 将服务注入到 app 中,供路由使用
|
||||
app.set('libraryService', libraryService);
|
||||
app.set('imageService', imageService);
|
||||
app.set('scanService', scanService);
|
||||
app.set('fileService', fileService);
|
||||
|
||||
// API 路由
|
||||
const libraryRouter = require('./routes/library');
|
||||
const imageRouter = require('./routes/image');
|
||||
const scanRouter = require('./routes/scan');
|
||||
const fileRouter = require('./routes/file');
|
||||
|
||||
app.use('/api/library', libraryRouter);
|
||||
app.use('/api/image', imageRouter);
|
||||
app.use('/api/scan', scanRouter);
|
||||
app.use('/api/file', fileRouter);
|
||||
|
||||
// 健康检查
|
||||
app.get('/api/health', (req, res) => {
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* 文件操作路由
|
||||
* 提供删除、重命名、移动、复制等文件操作接口
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { asyncHandler } = require('../middleware/errorHandler');
|
||||
|
||||
// 服务实例(从 app 中获取)
|
||||
let fileService;
|
||||
|
||||
router.use((req, res, next) => {
|
||||
if (!fileService) {
|
||||
fileService = req.app.get('fileService');
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
/**
|
||||
* 删除文件或文件夹(移到临时文件夹,5分钟内可撤销)
|
||||
* DELETE /api/file/delete
|
||||
* Body: { libraryId, items: [{type, path}] }
|
||||
*/
|
||||
router.delete('/delete', asyncHandler(async (req, res) => {
|
||||
const { libraryId, items } = req.body;
|
||||
|
||||
if (!libraryId || !items || !Array.isArray(items)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: '缺少必要参数'
|
||||
});
|
||||
}
|
||||
|
||||
const results = await fileService.deleteItems(libraryId, items);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: results
|
||||
});
|
||||
}));
|
||||
|
||||
/**
|
||||
* 重命名文件或文件夹
|
||||
* PATCH /api/file/rename
|
||||
* Body: { libraryId, path, newName }
|
||||
*/
|
||||
router.patch('/rename', asyncHandler(async (req, res) => {
|
||||
const { libraryId, path, newName } = req.body;
|
||||
|
||||
if (!libraryId || !path || !newName) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: '缺少必要参数'
|
||||
});
|
||||
}
|
||||
|
||||
const result = await fileService.renameItem(libraryId, path, newName);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: result
|
||||
});
|
||||
}));
|
||||
|
||||
/**
|
||||
* 移动文件或文件夹
|
||||
* POST /api/file/move
|
||||
* Body: { libraryId, items: [{type, path}], targetFolder }
|
||||
*/
|
||||
router.post('/move', asyncHandler(async (req, res) => {
|
||||
const { libraryId, items, targetFolder } = req.body;
|
||||
|
||||
if (!libraryId || !items || !Array.isArray(items) || targetFolder === undefined) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: '缺少必要参数'
|
||||
});
|
||||
}
|
||||
|
||||
const results = await fileService.moveItems(libraryId, items, targetFolder);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: results
|
||||
});
|
||||
}));
|
||||
|
||||
/**
|
||||
* 复制文件或文件夹
|
||||
* POST /api/file/copy
|
||||
* Body: { libraryId, items: [{type, path}], targetFolder }
|
||||
*/
|
||||
router.post('/copy', asyncHandler(async (req, res) => {
|
||||
const { libraryId, items, targetFolder } = req.body;
|
||||
|
||||
if (!libraryId || !items || !Array.isArray(items) || !targetFolder) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: '缺少必要参数'
|
||||
});
|
||||
}
|
||||
|
||||
const results = await fileService.copyItems(libraryId, items, targetFolder);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: results
|
||||
});
|
||||
}));
|
||||
|
||||
/**
|
||||
* 更新文件元数据(评分、收藏、标签)
|
||||
* PATCH /api/file/metadata
|
||||
* Body: { libraryId, path, rating?, favorite?, tags? }
|
||||
*/
|
||||
router.patch('/metadata', asyncHandler(async (req, res) => {
|
||||
const { libraryId, path, ...metadata } = req.body;
|
||||
|
||||
if (!libraryId || !path) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: '缺少必要参数'
|
||||
});
|
||||
}
|
||||
|
||||
const result = await fileService.updateMetadata(libraryId, path, metadata);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: result
|
||||
});
|
||||
}));
|
||||
|
||||
/**
|
||||
* 恢复文件
|
||||
*/
|
||||
router.post('/restore', asyncHandler(async (req, res) => {
|
||||
const { libraryId, items } = req.body;
|
||||
|
||||
if (!libraryId) {
|
||||
throw new ValidationError('libraryId');
|
||||
}
|
||||
|
||||
if (!Array.isArray(items) || items.length === 0) {
|
||||
throw new ValidationError('items');
|
||||
}
|
||||
|
||||
const fileService = req.app.get('fileService');
|
||||
const result = await fileService.restoreItems(libraryId, items);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: result
|
||||
});
|
||||
}));
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,751 @@
|
||||
/**
|
||||
* 文件操作服务
|
||||
* 提供删除、重命名、移动、复制等文件操作功能
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { processImage } = require('../../utils/scanner');
|
||||
|
||||
// 临时备份目录(用于撤销恢复)- 放在 .flypic 内部
|
||||
const TEMP_BACKUP_DIR = '.flypic/temp_backup';
|
||||
|
||||
class FileService {
|
||||
constructor(dbPool, configManager) {
|
||||
this.dbPool = dbPool;
|
||||
this.configManager = configManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复文件(从临时备份恢复)
|
||||
* @param {string} libraryId - 素材库ID
|
||||
* @param {Array} items - 待恢复项 [{type: 'file'|'folder', path: 'relative/path'}]
|
||||
*/
|
||||
async restoreItems(libraryId, items) {
|
||||
const db = this._getDatabase(libraryId);
|
||||
const libraryPath = db.libraryPath;
|
||||
const backupDir = path.join(libraryPath, TEMP_BACKUP_DIR);
|
||||
const results = { success: [], failed: [] };
|
||||
|
||||
if (!fs.existsSync(backupDir)) {
|
||||
throw new Error('备份目录不存在,无法恢复');
|
||||
}
|
||||
|
||||
for (const item of items) {
|
||||
try {
|
||||
const backupPath = path.join(backupDir, item.path);
|
||||
const originalPath = path.join(libraryPath, item.path);
|
||||
const metaPath = backupPath + '.meta.json';
|
||||
|
||||
console.log(`🔄 开始恢复: ${item.path} (${item.type})`);
|
||||
|
||||
// 检查备份是否存在
|
||||
if (!fs.existsSync(backupPath)) {
|
||||
results.failed.push({ path: item.path, error: '备份不存在(可能已超过5分钟被清理)' });
|
||||
continue;
|
||||
}
|
||||
|
||||
// 确保目标目录存在
|
||||
const targetDir = path.dirname(originalPath);
|
||||
if (!fs.existsSync(targetDir)) {
|
||||
fs.mkdirSync(targetDir, { recursive: true });
|
||||
}
|
||||
|
||||
// 读取元数据文件(包含数据库记录)
|
||||
let imageRecords = null;
|
||||
let folderRecords = null;
|
||||
if (fs.existsSync(metaPath)) {
|
||||
try {
|
||||
const metaContent = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
|
||||
imageRecords = metaContent.imageRecords;
|
||||
folderRecords = metaContent.folderRecords;
|
||||
console.log(` 读取到 ${Array.isArray(imageRecords) ? imageRecords.length : (imageRecords ? 1 : 0)} 条图片记录`);
|
||||
console.log(` 读取到 ${folderRecords ? folderRecords.length : 0} 条文件夹记录`);
|
||||
} catch (error) {
|
||||
console.warn(`读取meta失败 ${metaPath}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// 移动回原位置
|
||||
try {
|
||||
fs.renameSync(backupPath, originalPath);
|
||||
} catch (renameError) {
|
||||
console.log(` ⚠️ rename失败,使用复制方式`);
|
||||
// rename 失败时使用复制+删除
|
||||
if (item.type === 'folder') {
|
||||
this._copyDirSync(backupPath, originalPath);
|
||||
fs.rmSync(backupPath, { recursive: true, force: true });
|
||||
} else {
|
||||
fs.copyFileSync(backupPath, originalPath);
|
||||
fs.unlinkSync(backupPath);
|
||||
}
|
||||
}
|
||||
|
||||
// 恢复数据库记录(先文件夹后图片)
|
||||
if (folderRecords && folderRecords.length > 0) {
|
||||
for (const folderRecord of folderRecords) {
|
||||
try {
|
||||
const stmt = db.db.prepare(
|
||||
'INSERT OR REPLACE INTO folders (path, parent_path, name, image_count, last_scan) VALUES (?, ?, ?, ?, ?)'
|
||||
);
|
||||
stmt.run(
|
||||
folderRecord.path,
|
||||
folderRecord.parent_path || null,
|
||||
folderRecord.name,
|
||||
folderRecord.image_count || 0,
|
||||
folderRecord.last_scan || Date.now()
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn(`恢复文件夹记录失败: ${folderRecord.path}`, error);
|
||||
}
|
||||
}
|
||||
} else if (item.type === 'folder') {
|
||||
// 空文件夹没有数据库记录,需要重新创建
|
||||
try {
|
||||
const folderName = path.basename(item.path);
|
||||
const parentPath = path.dirname(item.path);
|
||||
const stmt = db.db.prepare(
|
||||
'INSERT OR REPLACE INTO folders (path, parent_path, name, image_count, last_scan) VALUES (?, ?, ?, ?, ?)'
|
||||
);
|
||||
stmt.run(
|
||||
item.path,
|
||||
parentPath === '.' ? null : parentPath,
|
||||
folderName,
|
||||
0,
|
||||
Date.now()
|
||||
);
|
||||
console.log(` 创建空文件夹记录: ${item.path}`);
|
||||
} catch (error) {
|
||||
console.warn(`创建文件夹记录失败: ${item.path}`, error);
|
||||
}
|
||||
}
|
||||
|
||||
if (imageRecords) {
|
||||
const records = Array.isArray(imageRecords) ? imageRecords : [imageRecords];
|
||||
for (const record of records) {
|
||||
try {
|
||||
db.insertImage(record);
|
||||
} catch (error) {
|
||||
console.warn(`恢复图片记录失败: ${record.path}`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 删除元数据文件
|
||||
if (fs.existsSync(metaPath)) {
|
||||
fs.unlinkSync(metaPath);
|
||||
}
|
||||
|
||||
results.success.push(item.path);
|
||||
console.log(`✅ 恢复成功: ${item.path}`);
|
||||
} catch (error) {
|
||||
console.error(`恢复失败 ${item.path}:`, error);
|
||||
results.failed.push({ path: item.path, error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
// 如果备份目录为空,删除它
|
||||
try {
|
||||
const files = fs.readdirSync(backupDir);
|
||||
if (files.length === 0) {
|
||||
fs.rmdirSync(backupDir);
|
||||
}
|
||||
} catch (error) {
|
||||
// 忽略错误
|
||||
}
|
||||
|
||||
// 更新文件夹计数(关键:确保计数准确)
|
||||
if (results.success.length > 0) {
|
||||
db.updateAllFolderCounts();
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理过期的临时文件(超过5分钟的移入回收站)
|
||||
* @param {string} libraryId - 素材库ID
|
||||
*/
|
||||
async cleanExpiredTempFiles(libraryId) {
|
||||
const db = this._getDatabase(libraryId);
|
||||
const libraryPath = db.libraryPath;
|
||||
const backupDir = path.join(libraryPath, TEMP_BACKUP_DIR);
|
||||
|
||||
if (!fs.existsSync(backupDir)) {
|
||||
return { cleaned: 0, failed: 0 };
|
||||
}
|
||||
|
||||
const FIVE_MINUTES = 5 * 60 * 1000; // 5分钟
|
||||
const now = Date.now();
|
||||
let cleaned = 0;
|
||||
let failed = 0;
|
||||
|
||||
// 递归扫描备份目录
|
||||
const scanDir = async (dir) => {
|
||||
const files = fs.readdirSync(dir);
|
||||
|
||||
for (const file of files) {
|
||||
const fullPath = path.join(dir, file);
|
||||
|
||||
// 跳过 meta 文件
|
||||
if (file.endsWith('.meta.json')) continue;
|
||||
|
||||
const metaPath = fullPath + '.meta.json';
|
||||
|
||||
// 检查是否有对应的 meta 文件
|
||||
if (fs.existsSync(metaPath)) {
|
||||
try {
|
||||
const meta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
|
||||
const age = now - meta.deletedAt;
|
||||
|
||||
// 超过5分钟,移入系统回收站
|
||||
if (age > FIVE_MINUTES) {
|
||||
try {
|
||||
// trash v8 是 ESM 模块,需要使用动态 import
|
||||
const { default: trash } = await import('trash');
|
||||
await trash([fullPath]);
|
||||
fs.unlinkSync(metaPath); // 删除 meta 文件
|
||||
cleaned++;
|
||||
console.log(`🗑️ 已将过期文件移入回收站: ${meta.originalPath}`);
|
||||
} catch (error) {
|
||||
console.error(`清理失败 ${meta.originalPath}:`, error);
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`读取 meta 失败 ${metaPath}:`, error);
|
||||
}
|
||||
} else if (fs.statSync(fullPath).isDirectory()) {
|
||||
// 递归处理子目录
|
||||
await scanDir(fullPath);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
await scanDir(backupDir);
|
||||
|
||||
// 清理完成后,递归删除所有空文件夹
|
||||
const removeEmptyDirs = (dir) => {
|
||||
try {
|
||||
// 检查目录是否存在
|
||||
if (!fs.existsSync(dir)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 读取目录内容
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(dir);
|
||||
} catch (error) {
|
||||
// 目录可能已被删除或无权限访问
|
||||
return;
|
||||
}
|
||||
|
||||
// 先递归处理所有子目录
|
||||
for (const entry of entries) {
|
||||
const fullPath = path.join(dir, entry);
|
||||
try {
|
||||
// 检查是否存在且为目录
|
||||
if (fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory()) {
|
||||
removeEmptyDirs(fullPath);
|
||||
}
|
||||
} catch (error) {
|
||||
// 文件可能在处理过程中被删除,忽略
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// 再次检查当前目录是否为空(因为子目录可能已被删除)
|
||||
let remainingFiles;
|
||||
try {
|
||||
remainingFiles = fs.readdirSync(dir);
|
||||
} catch (error) {
|
||||
// 目录可能已被删除
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果目录为空,则删除它(除了根 temp_backup 目录)
|
||||
if (remainingFiles.length === 0) {
|
||||
if (dir === backupDir) {
|
||||
// 根目录也删除(如果完全为空)
|
||||
try {
|
||||
fs.rmdirSync(dir);
|
||||
console.log(`🧹 已删除空的备份目录: ${TEMP_BACKUP_DIR}`);
|
||||
} catch (error) {
|
||||
// 忽略根目录删除失败
|
||||
}
|
||||
} else {
|
||||
// 子目录删除
|
||||
try {
|
||||
fs.rmdirSync(dir);
|
||||
const relativePath = path.relative(backupDir, dir);
|
||||
console.log(`🧹 已删除空文件夹: ${relativePath}`);
|
||||
} catch (error) {
|
||||
// 忽略删除失败(可能权限问题)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// 忽略所有其他错误
|
||||
}
|
||||
};
|
||||
|
||||
// 执行清理空文件夹
|
||||
try {
|
||||
removeEmptyDirs(backupDir);
|
||||
} catch (error) {
|
||||
console.warn('[cleanExpiredTempFiles] 清理空文件夹时出错:', error.message);
|
||||
}
|
||||
|
||||
return { cleaned, failed };
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归复制目录
|
||||
*/
|
||||
_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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据库实例
|
||||
*/
|
||||
_getDatabase(libraryId) {
|
||||
const config = this.configManager.load();
|
||||
const library = config.libraries.find(lib => lib.id === libraryId);
|
||||
if (!library) {
|
||||
throw new Error(`素材库不存在: ${libraryId}`);
|
||||
}
|
||||
return this.dbPool.acquire(library.path);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除文件或文件夹(移到临时文件夹,5分钟内可撤销)
|
||||
* @param {string} libraryId - 素材库ID
|
||||
* @param {Array} items - 待删除项 [{type: 'file'|'folder', path: 'relative/path'}]
|
||||
*/
|
||||
async deleteItems(libraryId, items) {
|
||||
const db = this._getDatabase(libraryId);
|
||||
const libraryPath = db.libraryPath;
|
||||
const results = { success: [], failed: [] };
|
||||
|
||||
for (const item of items) {
|
||||
try {
|
||||
const fullPath = path.join(libraryPath, item.path);
|
||||
|
||||
// 检查文件/文件夹是否存在
|
||||
if (!fs.existsSync(fullPath)) {
|
||||
if (item.type === 'folder') {
|
||||
// 物理文件夹已不存在:视为只需要清理数据库中的“空壳”记录
|
||||
console.warn(`目标文件夹不存在,仅清理数据库记录: ${item.path}`);
|
||||
try {
|
||||
db.deleteImagesByFolderPrefix(item.path);
|
||||
db.deleteFoldersByPrefix(item.path);
|
||||
results.success.push(item.path);
|
||||
} catch (e) {
|
||||
console.error(`清理不存在文件夹的数据库记录失败 ${item.path}:`, e.message);
|
||||
results.failed.push({ path: item.path, error: e.message });
|
||||
}
|
||||
} else {
|
||||
// 文件不存在仍然视为失败,提示用户
|
||||
results.failed.push({ path: item.path, error: '文件不存在' });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// 移到临时备份文件夹(5分钟内可撤销)
|
||||
const backupDir = path.join(libraryPath, TEMP_BACKUP_DIR);
|
||||
if (!fs.existsSync(backupDir)) {
|
||||
fs.mkdirSync(backupDir, { recursive: true });
|
||||
}
|
||||
|
||||
const backupPath = path.join(backupDir, item.path);
|
||||
const backupParentDir = path.dirname(backupPath);
|
||||
|
||||
// 确保备份目录存在
|
||||
if (!fs.existsSync(backupParentDir)) {
|
||||
fs.mkdirSync(backupParentDir, { recursive: true });
|
||||
}
|
||||
|
||||
// 移动文件到备份目录
|
||||
try {
|
||||
// 尝试直接 rename(快速)
|
||||
fs.renameSync(fullPath, backupPath);
|
||||
} catch (renameError) {
|
||||
// rename 失败(可能是权限问题或跨磁盘),使用复制+删除
|
||||
console.log(`⚠️ rename失败,使用复制方式: ${item.path}`);
|
||||
if (item.type === 'folder') {
|
||||
// 文件夹:递归复制
|
||||
this._copyDirSync(fullPath, backupPath);
|
||||
// 删除原文件夹
|
||||
fs.rmSync(fullPath, { recursive: true, force: true });
|
||||
} else {
|
||||
// 文件:直接复制
|
||||
fs.copyFileSync(fullPath, backupPath);
|
||||
fs.unlinkSync(fullPath);
|
||||
}
|
||||
}
|
||||
|
||||
// 记录删除时间(用于5分钟后清理)
|
||||
const metaPath = backupPath + '.meta.json';
|
||||
fs.writeFileSync(metaPath, JSON.stringify({
|
||||
originalPath: item.path,
|
||||
deletedAt: Date.now(),
|
||||
type: item.type
|
||||
}));
|
||||
|
||||
console.log(`📦 已移入临时文件夹: ${item.path}`);
|
||||
|
||||
// 删除数据库记录前,先保存到meta(恢复时需要)
|
||||
let imageRecords = null;
|
||||
let folderRecords = null;
|
||||
|
||||
if (item.type === 'folder') {
|
||||
// 保存文件夹内所有图片和文件夹的数据库记录
|
||||
imageRecords = db.getImagesByFolderPrefix(item.path);
|
||||
const stmt = db.db.prepare('SELECT * FROM folders WHERE path = ? OR path LIKE ?');
|
||||
folderRecords = stmt.all(item.path, `${item.path}/%`);
|
||||
|
||||
console.log(`🔍 删除文件夹: ${item.path} (图片:${imageRecords?.length || 0}, 子文件夹:${folderRecords?.length || 0})`);
|
||||
|
||||
// 删除数据库记录
|
||||
db.deleteImagesByFolderPrefix(item.path);
|
||||
db.deleteFoldersByPrefix(item.path);
|
||||
} else {
|
||||
// 保存单个文件的数据库记录
|
||||
imageRecords = db.getImageByPath(item.path);
|
||||
db.deleteImage(item.path);
|
||||
}
|
||||
|
||||
// 更新meta文件,包含数据库记录(只保存非空记录)
|
||||
const metaContent = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
|
||||
if (imageRecords && (Array.isArray(imageRecords) ? imageRecords.length > 0 : true)) {
|
||||
metaContent.imageRecords = imageRecords;
|
||||
}
|
||||
if (folderRecords && folderRecords.length > 0) {
|
||||
metaContent.folderRecords = folderRecords;
|
||||
}
|
||||
fs.writeFileSync(metaPath, JSON.stringify(metaContent));
|
||||
|
||||
// 删除缩略图(可选,因为缩略图基于 hash,可能被其他文件共享)
|
||||
// this._deleteThumbnail(db, item.path);
|
||||
|
||||
results.success.push(item.path);
|
||||
} catch (error) {
|
||||
console.error(`删除失败 ${item.path}:`, error.message);
|
||||
results.failed.push({ path: item.path, error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
// 更新文件夹计数
|
||||
if (results.success.length > 0) {
|
||||
db.updateAllFolderCounts();
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归复制文件夹(辅助方法)
|
||||
* @private
|
||||
*/
|
||||
_copyDirSync(src, dest) {
|
||||
// 创建目标目录
|
||||
if (!fs.existsSync(dest)) {
|
||||
fs.mkdirSync(dest, { recursive: true });
|
||||
}
|
||||
|
||||
// 读取源目录内容
|
||||
const entries = fs.readdirSync(src, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const srcPath = path.join(src, entry.name);
|
||||
const destPath = path.join(dest, entry.name);
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
// 递归复制子目录
|
||||
this._copyDirSync(srcPath, destPath);
|
||||
} else {
|
||||
// 复制文件
|
||||
fs.copyFileSync(srcPath, destPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重命名文件或文件夹
|
||||
* @param {string} libraryId - 素材库ID
|
||||
* @param {string} oldPath - 旧路径(相对路径)
|
||||
* @param {string} newName - 新名称(不含路径)
|
||||
*/
|
||||
async renameItem(libraryId, oldPath, newName) {
|
||||
const db = this._getDatabase(libraryId);
|
||||
const libraryPath = db.libraryPath;
|
||||
|
||||
const fullOldPath = path.join(libraryPath, oldPath);
|
||||
const directory = path.dirname(fullOldPath);
|
||||
const fullNewPath = path.join(directory, newName);
|
||||
|
||||
// 检查文件是否存在
|
||||
if (!fs.existsSync(fullOldPath)) {
|
||||
throw new Error('文件不存在');
|
||||
}
|
||||
|
||||
// 检查新名称是否已存在
|
||||
if (fs.existsSync(fullNewPath)) {
|
||||
// 自动添加编号
|
||||
const ext = path.extname(newName);
|
||||
const basename = path.basename(newName, ext);
|
||||
let counter = 1;
|
||||
let finalNewPath = fullNewPath;
|
||||
|
||||
while (fs.existsSync(finalNewPath)) {
|
||||
const numberedName = `${basename} (${counter})${ext}`;
|
||||
finalNewPath = path.join(directory, numberedName);
|
||||
counter++;
|
||||
}
|
||||
|
||||
fs.renameSync(fullOldPath, finalNewPath);
|
||||
|
||||
// 更新数据库
|
||||
const newRelativePath = path.relative(libraryPath, finalNewPath).replace(/\\/g, '/');
|
||||
this._updatePathInDatabase(db, oldPath, newRelativePath);
|
||||
|
||||
return { newPath: newRelativePath, newName: path.basename(finalNewPath) };
|
||||
}
|
||||
|
||||
// 执行重命名
|
||||
fs.renameSync(fullOldPath, fullNewPath);
|
||||
|
||||
// 更新数据库
|
||||
const newRelativePath = path.relative(libraryPath, fullNewPath).replace(/\\/g, '/');
|
||||
this._updatePathInDatabase(db, oldPath, newRelativePath);
|
||||
|
||||
return { newPath: newRelativePath, newName };
|
||||
}
|
||||
|
||||
/**
|
||||
* 移动文件或文件夹
|
||||
* @param {string} libraryId - 素材库ID
|
||||
* @param {Array} items - 待移动项
|
||||
* @param {string} targetFolder - 目标文件夹(相对路径)
|
||||
*/
|
||||
async moveItems(libraryId, items, targetFolder) {
|
||||
const db = this._getDatabase(libraryId);
|
||||
const libraryPath = db.libraryPath;
|
||||
const results = { success: [], failed: [] };
|
||||
|
||||
for (const item of items) {
|
||||
try {
|
||||
const oldFullPath = path.join(libraryPath, item.path);
|
||||
const fileName = path.basename(item.path);
|
||||
const newFullPath = path.join(libraryPath, targetFolder, fileName);
|
||||
|
||||
// 检查源文件是否存在
|
||||
if (!fs.existsSync(oldFullPath)) {
|
||||
results.failed.push({ path: item.path, error: '源文件不存在' });
|
||||
continue;
|
||||
}
|
||||
|
||||
// 检查目标文件夹是否存在
|
||||
const targetFullPath = path.join(libraryPath, targetFolder);
|
||||
if (!fs.existsSync(targetFullPath)) {
|
||||
fs.mkdirSync(targetFullPath, { recursive: true });
|
||||
}
|
||||
|
||||
// 检查目标是否已存在同名文件
|
||||
if (fs.existsSync(newFullPath)) {
|
||||
results.failed.push({ path: item.path, error: '目标位置已存在同名文件' });
|
||||
continue;
|
||||
}
|
||||
|
||||
// 移动文件(同分区使用 rename,跨分区自动降级为复制+删除)
|
||||
fs.renameSync(oldFullPath, newFullPath);
|
||||
|
||||
// 更新数据库
|
||||
const newRelativePath = path.relative(libraryPath, newFullPath).replace(/\\/g, '/');
|
||||
this._updatePathInDatabase(db, item.path, newRelativePath);
|
||||
|
||||
results.success.push({ oldPath: item.path, newPath: newRelativePath });
|
||||
} catch (error) {
|
||||
console.error(`移动失败 ${item.path}:`, error.message);
|
||||
results.failed.push({ path: item.path, error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
// 更新文件夹计数
|
||||
if (results.success.length > 0) {
|
||||
db.updateAllFolderCounts();
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制文件或文件夹
|
||||
* @param {string} libraryId - 素材库ID
|
||||
* @param {Array} items - 待复制项
|
||||
* @param {string} targetFolder - 目标文件夹(相对路径)
|
||||
*/
|
||||
async copyItems(libraryId, items, targetFolder) {
|
||||
const db = this._getDatabase(libraryId);
|
||||
const libraryPath = db.libraryPath;
|
||||
const results = { success: [], failed: [] };
|
||||
|
||||
for (const item of items) {
|
||||
try {
|
||||
const srcFullPath = path.join(libraryPath, item.path);
|
||||
const fileName = path.basename(item.path);
|
||||
const dstFullPath = path.join(libraryPath, targetFolder, fileName);
|
||||
|
||||
// 检查源文件是否存在
|
||||
if (!fs.existsSync(srcFullPath)) {
|
||||
results.failed.push({ path: item.path, error: '源文件不存在' });
|
||||
continue;
|
||||
}
|
||||
|
||||
// 确保目标文件夹存在
|
||||
const targetFullPath = path.join(libraryPath, targetFolder);
|
||||
if (!fs.existsSync(targetFullPath)) {
|
||||
fs.mkdirSync(targetFullPath, { recursive: true });
|
||||
}
|
||||
|
||||
// 处理同名文件
|
||||
let finalDstPath = dstFullPath;
|
||||
if (fs.existsSync(dstFullPath)) {
|
||||
const ext = path.extname(fileName);
|
||||
const basename = path.basename(fileName, ext);
|
||||
let counter = 1;
|
||||
|
||||
while (fs.existsSync(finalDstPath)) {
|
||||
const numberedName = `${basename} (${counter})${ext}`;
|
||||
finalDstPath = path.join(targetFullPath, numberedName);
|
||||
counter++;
|
||||
}
|
||||
}
|
||||
|
||||
// 复制文件或文件夹
|
||||
if (item.type === 'folder') {
|
||||
fs.cpSync(srcFullPath, finalDstPath, { recursive: true });
|
||||
// TODO: 递归处理文件夹中的所有图片
|
||||
} else {
|
||||
fs.copyFileSync(srcFullPath, finalDstPath);
|
||||
|
||||
// 处理新文件(生成缩略图、入库)
|
||||
await processImage(finalDstPath, libraryPath, db);
|
||||
}
|
||||
|
||||
const newRelativePath = path.relative(libraryPath, finalDstPath).replace(/\\/g, '/');
|
||||
results.success.push({ oldPath: item.path, newPath: newRelativePath });
|
||||
} catch (error) {
|
||||
console.error(`复制失败 ${item.path}:`, error.message);
|
||||
results.failed.push({ path: item.path, error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
// 更新文件夹计数
|
||||
if (results.success.length > 0) {
|
||||
db.updateAllFolderCounts();
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新文件元数据(评分、收藏、标签)
|
||||
* @param {string} libraryId - 素材库ID
|
||||
* @param {string} imagePath - 图片路径(相对路径)
|
||||
* @param {Object} metadata - 元数据 {rating, favorite, tags}
|
||||
*/
|
||||
async updateMetadata(libraryId, imagePath, metadata) {
|
||||
const db = this._getDatabase(libraryId);
|
||||
|
||||
const updates = {};
|
||||
if (metadata.rating !== undefined) updates.rating = metadata.rating;
|
||||
if (metadata.favorite !== undefined) updates.favorite = metadata.favorite;
|
||||
if (metadata.tags !== undefined) {
|
||||
updates.tags = Array.isArray(metadata.tags)
|
||||
? JSON.stringify(metadata.tags)
|
||||
: metadata.tags;
|
||||
}
|
||||
|
||||
if (Object.keys(updates).length === 0) {
|
||||
throw new Error('没有要更新的元数据');
|
||||
}
|
||||
|
||||
// 构建 SQL 更新语句
|
||||
const fields = Object.keys(updates).map(key => `${key} = ?`).join(', ');
|
||||
const values = [...Object.values(updates), imagePath];
|
||||
|
||||
const stmt = db.db.prepare(`UPDATE images SET ${fields} WHERE path = ?`);
|
||||
const result = stmt.run(...values);
|
||||
|
||||
if (result.changes === 0) {
|
||||
throw new Error('图片不存在');
|
||||
}
|
||||
|
||||
// 更新数据库修改时间
|
||||
db.updateLastModified();
|
||||
|
||||
return db.getImageByPath(imagePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新数据库中的路径(私有方法)
|
||||
*/
|
||||
_updatePathInDatabase(db, oldPath, newPath) {
|
||||
const image = db.getImageByPath(oldPath);
|
||||
if (!image) return;
|
||||
|
||||
// 更新路径和文件名
|
||||
const newFilename = path.basename(newPath);
|
||||
const newFolder = path.dirname(newPath);
|
||||
|
||||
const stmt = db.db.prepare(`
|
||||
UPDATE images
|
||||
SET path = ?, filename = ?, folder = ?
|
||||
WHERE path = ?
|
||||
`);
|
||||
|
||||
stmt.run(
|
||||
newPath,
|
||||
newFilename,
|
||||
newFolder === '.' ? '' : newFolder.replace(/\\/g, '/'),
|
||||
oldPath
|
||||
);
|
||||
|
||||
db.updateLastModified();
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除缩略图(私有方法)
|
||||
*/
|
||||
_deleteThumbnail(db, imagePath) {
|
||||
const image = db.getImageByPath(imagePath);
|
||||
if (!image || !image.thumbnail_path) return;
|
||||
|
||||
try {
|
||||
const thumbnailFullPath = path.join(db.libraryPath, image.thumbnail_path);
|
||||
if (fs.existsSync(thumbnailFullPath)) {
|
||||
fs.unlinkSync(thumbnailFullPath);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`删除缩略图失败: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = FileService;
|
||||
@@ -180,13 +180,14 @@ class LightweightWatcher {
|
||||
|
||||
try {
|
||||
// 获取数据库中这些文件夹的文件列表
|
||||
// 🔥 关键修复:只查询文件夹直接包含的文件,不包含子文件夹
|
||||
// 因为 _scanFolder 不递归扫描,如果这里包含子文件夹,会误删子文件夹的记录
|
||||
const dbFiles = new Set();
|
||||
for (const folder of changedFolders) {
|
||||
const relativePath = path.relative(libraryPath, folder).replace(/\\/g, '/');
|
||||
// 使用正确的 SQL 模式匹配
|
||||
const pattern = relativePath ? `${relativePath}/%` : '%';
|
||||
const stmt = db.db.prepare('SELECT path FROM images WHERE folder = ? OR folder LIKE ?');
|
||||
const rows = stmt.all(relativePath, pattern);
|
||||
// 只查询 folder = ? 的记录,不包含子文件夹(去掉 OR folder LIKE ?/%)
|
||||
const stmt = db.db.prepare('SELECT path FROM images WHERE folder = ?');
|
||||
const rows = stmt.all(relativePath);
|
||||
rows.forEach(row => dbFiles.add(row.path));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* 文件操作 API 客户端
|
||||
*/
|
||||
|
||||
import axios from 'axios';
|
||||
|
||||
const API_BASE = import.meta.env.VITE_API_BASE || 'http://localhost:15002';
|
||||
|
||||
export const fileAPI = {
|
||||
/**
|
||||
* 删除文件或文件夹(移到临时文件夹,5分钟内可撤销)
|
||||
* @param {string} libraryId - 素材库ID
|
||||
* @param {Array} items - 待删除项 [{type: 'file'|'folder', path: 'path'}]
|
||||
*/
|
||||
async delete(libraryId, items) {
|
||||
const response = await axios.delete(`${API_BASE}/api/file/delete`, {
|
||||
data: { libraryId, items }
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
|
||||
/**
|
||||
* 重命名文件或文件夹
|
||||
* @param {string} libraryId - 素材库ID
|
||||
* @param {string} path - 文件路径
|
||||
* @param {string} newName - 新名称
|
||||
*/
|
||||
async rename(libraryId, path, newName) {
|
||||
const response = await axios.patch(`${API_BASE}/api/file/rename`, {
|
||||
libraryId,
|
||||
path,
|
||||
newName
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
|
||||
/**
|
||||
* 移动文件或文件夹
|
||||
* @param {string} libraryId - 素材库ID
|
||||
* @param {Array} items - 待移动项
|
||||
* @param {string} targetFolder - 目标文件夹路径
|
||||
*/
|
||||
async move(libraryId, items, targetFolder) {
|
||||
const response = await axios.post(`${API_BASE}/api/file/move`, {
|
||||
libraryId,
|
||||
items,
|
||||
targetFolder
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
|
||||
/**
|
||||
* 复制文件或文件夹
|
||||
* @param {string} libraryId - 素材库ID
|
||||
* @param {Array} items - 待复制项
|
||||
* @param {string} targetFolder - 目标文件夹路径
|
||||
*/
|
||||
async copy(libraryId, items, targetFolder) {
|
||||
const response = await axios.post(`${API_BASE}/api/file/copy`, {
|
||||
libraryId,
|
||||
items,
|
||||
targetFolder
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
|
||||
/**
|
||||
* 更新文件元数据(评分、收藏、标签)
|
||||
* @param {string} libraryId - 素材库ID
|
||||
* @param {string} path - 文件路径
|
||||
* @param {Object} metadata - 元数据 {rating?, favorite?, tags?}
|
||||
*/
|
||||
async updateMetadata(libraryId, path, metadata) {
|
||||
const response = await axios.patch(`${API_BASE}/api/file/metadata`, {
|
||||
libraryId,
|
||||
path,
|
||||
...metadata
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
|
||||
/**
|
||||
* 恢复文件或文件夹(从临时备份恢复)
|
||||
* @param {string} libraryId - 素材库ID
|
||||
* @param {Array} items - 待恢复项 [{type: 'file'|'folder', path: 'path'}]
|
||||
*/
|
||||
async restore(libraryId, items) {
|
||||
const response = await axios.post(`${API_BASE}/api/file/restore`, {
|
||||
libraryId,
|
||||
items
|
||||
});
|
||||
return response.data;
|
||||
}
|
||||
};
|
||||
@@ -5,10 +5,12 @@
|
||||
import * as library from './endpoints/library';
|
||||
import * as image from './endpoints/image';
|
||||
import * as scan from './endpoints/scan';
|
||||
import { fileAPI } from './file';
|
||||
|
||||
export const libraryAPI = library;
|
||||
export const imageAPI = image;
|
||||
export const scanAPI = scan;
|
||||
export { fileAPI };
|
||||
|
||||
export { api, APIError } from './client';
|
||||
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* 右键上下文菜单组件
|
||||
* 提供文件操作选项:删除、重命名、移动、复制
|
||||
*/
|
||||
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { Trash2, Edit3, Move, Copy } from 'lucide-react';
|
||||
|
||||
function ContextMenu({ isOpen, position, onClose, options }) {
|
||||
const menuRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
|
||||
const handleClickOutside = (e) => {
|
||||
if (menuRef.current && !menuRef.current.contains(e.target)) {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
const handleEscape = (e) => {
|
||||
if (e.key === 'Escape') {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
document.addEventListener('keydown', handleEscape);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handleClickOutside);
|
||||
document.removeEventListener('keydown', handleEscape);
|
||||
};
|
||||
}, [isOpen, onClose]);
|
||||
|
||||
if (!isOpen || !position) return null;
|
||||
|
||||
// 计算菜单位置,防止超出屏幕
|
||||
const menuStyle = {
|
||||
left: `${position.x}px`,
|
||||
top: `${position.y}px`,
|
||||
};
|
||||
|
||||
const handleOptionClick = (action) => {
|
||||
action();
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={menuRef}
|
||||
className="fixed z-50 bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-200 dark:border-gray-700 py-2 min-w-[200px]"
|
||||
style={menuStyle}
|
||||
>
|
||||
{options.map((option, index) => (
|
||||
<div key={index}>
|
||||
{option.divider ? (
|
||||
<div className="my-2 border-t border-gray-200 dark:border-gray-700" />
|
||||
) : (
|
||||
<button
|
||||
onClick={() => handleOptionClick(option.action)}
|
||||
disabled={option.disabled}
|
||||
className={`
|
||||
w-full flex items-center gap-3 px-4 py-2 text-left text-sm
|
||||
${option.disabled
|
||||
? 'opacity-50 cursor-not-allowed'
|
||||
: 'hover:bg-gray-100 dark:hover:bg-gray-700'
|
||||
}
|
||||
${option.danger
|
||||
? 'text-red-600 dark:text-red-400'
|
||||
: 'text-gray-700 dark:text-gray-300'
|
||||
}
|
||||
`}
|
||||
>
|
||||
{option.icon}
|
||||
<span className="flex-1">{option.label}</span>
|
||||
{option.shortcut && (
|
||||
<span className="text-xs text-gray-400 dark:text-gray-500">
|
||||
{option.shortcut}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 预定义常用菜单项
|
||||
export const menuItems = {
|
||||
delete: (action) => ({
|
||||
icon: <Trash2 size={16} />,
|
||||
label: '移入回收站',
|
||||
shortcut: 'Del',
|
||||
danger: false,
|
||||
action
|
||||
}),
|
||||
rename: (action) => ({
|
||||
icon: <Edit3 size={16} />,
|
||||
label: '重命名',
|
||||
shortcut: 'F2',
|
||||
action
|
||||
}),
|
||||
move: (action) => ({
|
||||
icon: <Move size={16} />,
|
||||
label: '移动到...',
|
||||
action
|
||||
}),
|
||||
copy: (action) => ({
|
||||
icon: <Copy size={16} />,
|
||||
label: '复制到...',
|
||||
shortcut: 'Ctrl+C',
|
||||
action
|
||||
}),
|
||||
divider: () => ({ divider: true })
|
||||
};
|
||||
|
||||
export default ContextMenu;
|
||||
@@ -7,9 +7,11 @@ import { useLibraryStore } from '../stores/useLibraryStore';
|
||||
import { useImageStore } from '../stores/useImageStore';
|
||||
import { useUIStore } from '../stores/useUIStore';
|
||||
import { useScanStore } from '../stores/useScanStore';
|
||||
import { imageAPI } from '../api';
|
||||
import { imageAPI, fileAPI } from '../api';
|
||||
import requestManager, { RequestType } from '../services/requestManager';
|
||||
import FileViewer from './FileViewer';
|
||||
import ContextMenu, { menuItems } from './ContextMenu';
|
||||
import UndoToast from './UndoToast';
|
||||
|
||||
// 虚拟滚动阈值:超过此数量启用虚拟滚动
|
||||
const VIRTUAL_SCROLL_THRESHOLD = 100;
|
||||
@@ -55,8 +57,8 @@ function ImageWaterfall() {
|
||||
const { currentLibraryId } = useLibraryStore();
|
||||
const {
|
||||
images, selectedImage, setSelectedImage, selectedImages, setSelectedImages,
|
||||
toggleImageSelection, clearSelection, imageLoadingState, selectedFolder,
|
||||
searchKeywords, filters, appendImages, setImageLoadingState
|
||||
toggleImageSelection, clearSelection, imageLoadingState, selectedFolder, setSelectedFolder,
|
||||
searchKeywords, filters, appendImages, setImageLoadingState, setImages, setFolders
|
||||
} = useImageStore();
|
||||
|
||||
const { thumbnailHeight, isResizingPanels } = useUIStore();
|
||||
@@ -112,6 +114,43 @@ function ImageWaterfall() {
|
||||
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([]); // 撤销历史栈,支持多次撤销
|
||||
|
||||
// 监听文件夹切换,切换时关闭Toast
|
||||
useEffect(() => {
|
||||
// 文件夹切换时立即关闭Toast,避免重新计时
|
||||
setUndoToast({ isVisible: false, message: '', count: 0 });
|
||||
}, [selectedFolder]);
|
||||
|
||||
// 全局快捷键监听 - Del 键删除, Ctrl+Z 撤销
|
||||
useEffect(() => {
|
||||
const handleGlobalKeyDown = async (e) => {
|
||||
// 忽略输入框中的快捷键
|
||||
if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
|
||||
|
||||
// Ctrl+Z → 撤销
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 'z') {
|
||||
e.preventDefault();
|
||||
if (undoHistory.length > 0) {
|
||||
await handleUndo();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Del 键 → 直接移入回收站
|
||||
if (e.key === 'Delete') {
|
||||
if (selectedImages.length > 0 || selectedImage) {
|
||||
e.preventDefault();
|
||||
await handleQuickDelete();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleGlobalKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleGlobalKeyDown);
|
||||
}, [selectedImages, selectedImage, images, currentLibraryId, undoHistory]);
|
||||
|
||||
// 简单的向下无限滚动加载
|
||||
const loadMoreImages = useCallback(async () => {
|
||||
@@ -412,6 +451,194 @@ function ImageWaterfall() {
|
||||
}
|
||||
}, [flatImages, lastSelectedIndex, toggleImageSelection, setSelectedImages, clearSelection, setSelectedImage]);
|
||||
|
||||
// 处理右键菜单
|
||||
const handleContextMenu = useCallback((e, image) => {
|
||||
e.preventDefault();
|
||||
setContextMenu({
|
||||
isOpen: true,
|
||||
position: { x: e.clientX, y: e.clientY },
|
||||
image
|
||||
});
|
||||
}, []);
|
||||
|
||||
// 撤销删除 - 乐观更新,立即响应
|
||||
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.data.failed.length > 0) {
|
||||
console.warn(`⚠️ 恢复失败: ${restoreResult.data.failed.length} 个文件`);
|
||||
const errorMsg = restoreResult.data.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 || '未知错误'));
|
||||
});
|
||||
};
|
||||
|
||||
// 快速删除(乐观更新,立即响应)
|
||||
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.data.failed.length > 0) {
|
||||
console.warn(`⚠️ 删除失败: ${deleteResult.data.failed.length} 个文件`, deleteResult.data.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 getContextMenuOptions = useCallback((image) => {
|
||||
return [
|
||||
menuItems.delete(async () => {
|
||||
setContextMenu({ isOpen: false, position: null, image: null });
|
||||
await handleQuickDelete();
|
||||
})
|
||||
];
|
||||
}, [selectedImages, selectedImage]);
|
||||
|
||||
// 渲染单个图片单元格
|
||||
const renderImageCell = (image, flatIndex) => {
|
||||
const isSingleSelected = selectedImage?.id === image.id;
|
||||
@@ -442,6 +669,15 @@ function ImageWaterfall() {
|
||||
setViewerFile(image);
|
||||
}
|
||||
}}
|
||||
onContextMenu={(e) => handleContextMenu(e, image)}
|
||||
draggable={true}
|
||||
onDragStart={(e) => {
|
||||
const items = selectedImages.length > 0 && selectedImages.some(img => img.id === image.id)
|
||||
? selectedImages
|
||||
: [image];
|
||||
e.dataTransfer.setData('flypic/images', JSON.stringify(items));
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={getThumbnailUrl(image) || 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="200" height="200"%3E%3Crect fill="%23f3f4f6" width="200" height="200"/%3E%3Ctext x="50%25" y="45%25" dominant-baseline="middle" text-anchor="middle" fill="%239ca3af" font-family="sans-serif" font-size="14"%3E需要同步%3C/text%3E%3Ctext x="50%25" y="60%25" dominant-baseline="middle" text-anchor="middle" fill="%23d1d5db" font-family="sans-serif" font-size="12"%3E点击同步按钮%3C/text%3E%3C/svg%3E'}
|
||||
@@ -607,6 +843,25 @@ function ImageWaterfall() {
|
||||
onClose={() => setViewerFile(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 右键菜单 */}
|
||||
<ContextMenu
|
||||
isOpen={contextMenu.isOpen}
|
||||
position={contextMenu.position}
|
||||
onClose={() => setContextMenu({ isOpen: false, position: null, image: null })}
|
||||
options={contextMenu.image ? getContextMenuOptions(contextMenu.image) : []}
|
||||
/>
|
||||
|
||||
{/* 撤销删除提示 */}
|
||||
<UndoToast
|
||||
isVisible={undoToast.isVisible}
|
||||
message={undoToast.message}
|
||||
onUndo={handleUndo}
|
||||
onClose={() => {
|
||||
setUndoToast({ isVisible: false, message: '', count: 0 });
|
||||
// 不清空历史栈,允许Toast消失后仍可Ctrl+Z
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -166,6 +166,17 @@ function MainContent() {
|
||||
};
|
||||
}, [currentLibraryId, searchKeywords, selectedFolder, loadImages, cancelCurrentRequest]);
|
||||
|
||||
// 恢复撤销前的文件夹状态
|
||||
useEffect(() => {
|
||||
const restoreFolder = localStorage.getItem('flypic_restore_folder');
|
||||
if (restoreFolder) {
|
||||
const { setSelectedFolder } = useImageStore.getState();
|
||||
setSelectedFolder(restoreFolder);
|
||||
localStorage.removeItem('flypic_restore_folder');
|
||||
console.log('✅ 已恢复到文件夹:', restoreFolder);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 组件卸载时清理
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
|
||||
@@ -4,12 +4,12 @@ import { useLibraryStore } from '../stores/useLibraryStore';
|
||||
import { useImageStore } from '../stores/useImageStore';
|
||||
import { useUIStore } from '../stores/useUIStore';
|
||||
import { useScanStore } from '../stores/useScanStore';
|
||||
import { imageAPI } from '../api';
|
||||
import { imageAPI, fileAPI } from '../api';
|
||||
import JSZip from 'jszip';
|
||||
|
||||
function RightPanel() {
|
||||
const { currentLibraryId } = useLibraryStore();
|
||||
const { selectedImage, selectedImages, selectedFolder, images } = useImageStore();
|
||||
const { selectedImage, selectedImages, selectedFolder, images, setSelectedImage } = useImageStore();
|
||||
const { setMobileView, isResizingPanels, resizingSide } = useUIStore();
|
||||
const [isMobile, setIsMobile] = useState(false);
|
||||
const [imageUrl, setImageUrl] = useState(''); // 当前显示的图片URL
|
||||
@@ -932,35 +932,34 @@ function RightPanel() {
|
||||
})()
|
||||
) : (
|
||||
// 单选模式
|
||||
<>
|
||||
<div>
|
||||
<span className="text-gray-500 dark:text-gray-400">文件名:</span>
|
||||
<p className="text-gray-900 dark:text-gray-100 break-all">{selectedImage.filename}</p>
|
||||
</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>
|
||||
</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>
|
||||
</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>
|
||||
</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>
|
||||
</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>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<>
|
||||
<div>
|
||||
<span className="text-gray-500 dark:text-gray-400">文件名:</span>
|
||||
<p className="text-gray-900 dark:text-gray-100 break-all">{selectedImage.filename}</p>
|
||||
</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>
|
||||
</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>
|
||||
</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>
|
||||
</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>
|
||||
</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>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div>
|
||||
<span className="text-gray-500 dark:text-gray-400">路径:</span>
|
||||
<div className="flex items-start gap-2 mt-1">
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { useState, useMemo, useEffect, useRef } from 'react';
|
||||
import { useState, useMemo, useEffect, useRef, useCallback } from 'react';
|
||||
import { Folder, Search, ChevronRight, ChevronDown, X, Trash2, ChevronsRight, ChevronsDown } from 'lucide-react';
|
||||
import { useLibraryStore } from '../stores/useLibraryStore';
|
||||
import { useImageStore } from '../stores/useImageStore';
|
||||
import { useScanStore } from '../stores/useScanStore';
|
||||
import { libraryAPI, scanAPI, imageAPI } from '../api';
|
||||
import { libraryAPI, scanAPI, imageAPI, fileAPI } from '../api';
|
||||
import requestManager from '../services/requestManager';
|
||||
import { onUserActionStart } from '../services/imageLoadService';
|
||||
import LibraryMissingModal from './LibraryMissingModal';
|
||||
import ContextMenu, { menuItems } from './ContextMenu';
|
||||
import UndoToast from './UndoToast';
|
||||
|
||||
// 检查素材库扫描状态
|
||||
const checkScanStatus = async (libraryId) => {
|
||||
@@ -43,6 +45,9 @@ function Sidebar() {
|
||||
const [isSwitching, setIsSwitching] = useState(false);
|
||||
const [missingLibrary, setMissingLibrary] = useState(null); // 切换时发现的丢失素材库
|
||||
const [isLibrarySelectorOpen, setIsLibrarySelectorOpen] = useState(false); // 素材库选择器展开状态
|
||||
const [contextMenu, setContextMenu] = useState({ isOpen: false, position: null, folder: null });
|
||||
const [undoToast, setUndoToast] = useState({ isVisible: false, message: '', count: 0 });
|
||||
const [undoHistory, setUndoHistory] = useState([]); // 撤销历史栈,支持多次撤销
|
||||
const folderSearchDebounceRef = useRef(null);
|
||||
const librarySelectorRef = useRef(null);
|
||||
|
||||
@@ -68,6 +73,12 @@ function Sidebar() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 监听文件夹切换,切换时关闭Toast
|
||||
useEffect(() => {
|
||||
// 文件夹切换时立即关闭Toast,避免重新计时
|
||||
setUndoToast({ isVisible: false, message: '', count: 0 });
|
||||
}, [selectedFolder]);
|
||||
|
||||
// 响应全局状态:显示新建素材库表单
|
||||
useEffect(() => {
|
||||
if (showAddLibraryForm) {
|
||||
@@ -98,6 +109,228 @@ function Sidebar() {
|
||||
}
|
||||
}, [isLibrarySelectorOpen]);
|
||||
|
||||
// 从树形结构中移除指定节点
|
||||
const removeNodeFromTree = useCallback((tree, targetPath) => {
|
||||
if (!tree || tree.length === 0) return tree;
|
||||
|
||||
return tree
|
||||
.filter(node => node.path !== targetPath)
|
||||
.map(node => ({
|
||||
...node,
|
||||
children: node.children ? removeNodeFromTree(node.children, targetPath) : []
|
||||
}));
|
||||
}, []);
|
||||
|
||||
// 智能选择删除文件夹后的下一个文件夹
|
||||
const findNextFolderAfterDelete = useCallback((deletedPath, allFolders) => {
|
||||
if (!allFolders || allFolders.length === 0) return null;
|
||||
|
||||
// 将树形结构拍平成一维列表,便于按 path / 父路径 处理
|
||||
const flat = [];
|
||||
const walk = (nodes) => {
|
||||
if (!nodes) return;
|
||||
for (const node of nodes) {
|
||||
flat.push(node);
|
||||
if (node.children && node.children.length > 0) {
|
||||
walk(node.children);
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(allFolders);
|
||||
|
||||
// 计算被删除文件夹的父级路径
|
||||
const parentPath = deletedPath.includes('/')
|
||||
? deletedPath.substring(0, deletedPath.lastIndexOf('/'))
|
||||
: null;
|
||||
|
||||
// 找出所有同级兄弟(包括被删除的那个)
|
||||
const siblings = flat.filter((f) => {
|
||||
const fParent = f.path.includes('/')
|
||||
? f.path.substring(0, f.path.lastIndexOf('/'))
|
||||
: null;
|
||||
return fParent === parentPath;
|
||||
});
|
||||
|
||||
if (siblings.length === 0) {
|
||||
// 没有任何同级,直接回退到父级或"全部"
|
||||
return parentPath || null;
|
||||
}
|
||||
|
||||
const deletedIndex = siblings.findIndex((f) => f.path === deletedPath);
|
||||
|
||||
if (deletedIndex === -1) {
|
||||
// 在当前树结构中已找不到该节点,保守地回退到父级/全部
|
||||
return parentPath || null;
|
||||
}
|
||||
|
||||
// 优先级1:同级下方
|
||||
if (deletedIndex < siblings.length - 1) {
|
||||
return siblings[deletedIndex + 1].path;
|
||||
}
|
||||
|
||||
// 优先级2:同级上方
|
||||
if (deletedIndex > 0) {
|
||||
return siblings[deletedIndex - 1].path;
|
||||
}
|
||||
|
||||
// 优先级3:父级
|
||||
return parentPath || null;
|
||||
}, []);
|
||||
|
||||
// 监听Del键删除选中的文件夹
|
||||
useEffect(() => {
|
||||
const handleKeyDown = async (e) => {
|
||||
// 忽略输入框中的快捷键
|
||||
if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
|
||||
|
||||
// Del 键 → 删除当前选中的文件夹(只在没有选中图片时)
|
||||
if (e.key === 'Delete' && selectedFolder) {
|
||||
const { selectedImages, selectedImage } = useImageStore.getState();
|
||||
// 如果有选中的图片,让 ImageWaterfall 处理删除
|
||||
if (selectedImages.length > 0 || selectedImage) return;
|
||||
|
||||
e.preventDefault();
|
||||
await handleDeleteFolder(selectedFolder);
|
||||
}
|
||||
|
||||
// Ctrl+Z → 撤销(文件夹或图片)
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 'z') {
|
||||
// 如果有文件夹撤销历史,撤销文件夹
|
||||
if (undoHistory.length > 0) {
|
||||
e.preventDefault();
|
||||
await handleUndoFolderDelete();
|
||||
}
|
||||
// 否则让 ImageWaterfall 处理图片撤销
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [selectedFolder, undoHistory, findNextFolderAfterDelete]);
|
||||
|
||||
// 文件夹删除功能(乐观更新,立即响应)
|
||||
const handleDeleteFolder = async (folderPath) => {
|
||||
if (!currentLibraryId) return;
|
||||
|
||||
const items = [{ type: 'folder', path: folderPath }];
|
||||
|
||||
// 1. 推入历史栈
|
||||
const newHistory = [...undoHistory, {
|
||||
items: items,
|
||||
folderPath: folderPath
|
||||
}];
|
||||
setUndoHistory(newHistory);
|
||||
|
||||
// 2. 如果删除的是当前选中的文件夹,智能选择下一个文件夹
|
||||
if (selectedFolder === folderPath) {
|
||||
// 先从当前 folders 树中移除即将被删除的节点,再计算下一个目标
|
||||
const foldersAfterDelete = removeNodeFromTree(folders, folderPath);
|
||||
const nextFolder = findNextFolderAfterDelete(folderPath, foldersAfterDelete);
|
||||
setSelectedFolder(nextFolder);
|
||||
}
|
||||
|
||||
// 3. 立即显示Toast
|
||||
setUndoToast({
|
||||
isVisible: true,
|
||||
message: `已将文件夹移入临时文件夹(Ctrl+Z撤销 · ${newHistory.length}次)`,
|
||||
count: 1
|
||||
});
|
||||
|
||||
// 4. 后台执行API调用(不阻塞UI)
|
||||
Promise.all([
|
||||
fileAPI.delete(currentLibraryId, items),
|
||||
imageAPI.getFolders(currentLibraryId)
|
||||
]).then(([deleteResult, foldersRes]) => {
|
||||
const { setFolders } = useImageStore.getState();
|
||||
if (deleteResult.data.failed.length > 0) {
|
||||
console.warn(`⚠️ 删除失败:`, deleteResult.data.failed);
|
||||
// 失败时回滚
|
||||
setUndoHistory(undoHistory);
|
||||
setUndoToast({ isVisible: false, message: '', count: 0 });
|
||||
setFolders(foldersRes.folders);
|
||||
alert('删除失败: ' + deleteResult.data.failed[0].error);
|
||||
} else {
|
||||
// 成功时刷新文件夹列表以确保同步
|
||||
setFolders(foldersRes.folders);
|
||||
}
|
||||
}).catch(error => {
|
||||
console.error('删除文件夹失败:', error);
|
||||
// 失败时回滚
|
||||
setUndoHistory(undoHistory);
|
||||
setUndoToast({ isVisible: false, message: '', count: 0 });
|
||||
imageAPI.getFolders(currentLibraryId).then(foldersRes => {
|
||||
const { setFolders } = useImageStore.getState();
|
||||
setFolders(foldersRes.folders);
|
||||
});
|
||||
alert('删除失败: ' + (error.message || '未知错误'));
|
||||
});
|
||||
};
|
||||
|
||||
// 撤销文件夹删除(乐观更新,立即响应)
|
||||
const handleUndoFolderDelete = 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 { folders, setFolders } = useImageStore.getState();
|
||||
if (folders && folders.length > 0) {
|
||||
// 检查文件夹是否已在列表中
|
||||
const folderExists = folders.some(f => f.path === lastDeleted.folderPath);
|
||||
if (!folderExists) {
|
||||
// 如果文件夹不在列表中,立即添加(占位符,后端会返回正确的计数)
|
||||
const newFolder = {
|
||||
path: lastDeleted.folderPath,
|
||||
count: 0, // 占位符,后端刷新时会更新
|
||||
name: lastDeleted.folderPath.split('/').pop() || lastDeleted.folderPath
|
||||
};
|
||||
setFolders([...folders, newFolder]);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 立即跳转到恢复的文件夹
|
||||
setSelectedFolder(lastDeleted.folderPath);
|
||||
console.log(`📂 跳转到文件夹: ${lastDeleted.folderPath}`);
|
||||
|
||||
// 5. 后台执行API调用(不阻塞UI)
|
||||
Promise.all([
|
||||
fileAPI.restore(currentLibraryId, lastDeleted.items),
|
||||
imageAPI.getFolders(currentLibraryId)
|
||||
]).then(([restoreResult, foldersRes]) => {
|
||||
const { setFolders } = useImageStore.getState();
|
||||
// 检查恢复结果
|
||||
if (restoreResult.data.failed.length > 0) {
|
||||
console.warn(`⚠️ 恢复失败: ${restoreResult.data.failed.length} 个文件`);
|
||||
const errorMsg = restoreResult.data.failed[0].error || '未知错误';
|
||||
|
||||
// 失败时回滚
|
||||
setUndoHistory(undoHistory);
|
||||
setFolders(foldersRes.folders);
|
||||
alert(`恢复失败: ${errorMsg}\n\n提示:超过5分钟的文件已移入系统回收站,请手动从回收站恢复。`);
|
||||
} else {
|
||||
// 成功时刷新文件夹列表以确保同步
|
||||
setFolders(foldersRes.folders);
|
||||
}
|
||||
}).catch(error => {
|
||||
console.error('撤销失败:', error);
|
||||
// 失败时回滚
|
||||
setUndoHistory(undoHistory);
|
||||
imageAPI.getFolders(currentLibraryId).then(foldersRes => {
|
||||
const { setFolders } = useImageStore.getState();
|
||||
setFolders(foldersRes.folders);
|
||||
});
|
||||
alert('撤销失败: ' + (error.message || '未知错误'));
|
||||
});
|
||||
};
|
||||
|
||||
const handleAddLibrary = async () => {
|
||||
// 扫描期间禁止添加素材库
|
||||
if (isScanning()) {
|
||||
@@ -485,6 +718,14 @@ function Sidebar() {
|
||||
}`}
|
||||
style={{ paddingLeft: `${level * 16 + 12}px` }}
|
||||
onClick={() => handleFolderClick(folder)}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
setContextMenu({
|
||||
isOpen: true,
|
||||
position: { x: e.clientX, y: e.clientY },
|
||||
folder: folder
|
||||
});
|
||||
}}
|
||||
>
|
||||
{/* 展开/折叠图标 - 独立点击区域 */}
|
||||
{hasChildren ? (
|
||||
@@ -798,6 +1039,30 @@ function Sidebar() {
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 文件夹右键菜单 */}
|
||||
<ContextMenu
|
||||
isOpen={contextMenu.isOpen}
|
||||
position={contextMenu.position}
|
||||
onClose={() => setContextMenu({ isOpen: false, position: null, folder: null })}
|
||||
options={contextMenu.folder ? [
|
||||
menuItems.delete(async () => {
|
||||
setContextMenu({ isOpen: false, position: null, folder: null });
|
||||
await handleDeleteFolder(contextMenu.folder.path);
|
||||
})
|
||||
] : []}
|
||||
/>
|
||||
|
||||
{/* 撤销删除提示 */}
|
||||
<UndoToast
|
||||
isVisible={undoToast.isVisible}
|
||||
message={undoToast.message}
|
||||
onUndo={handleUndoFolderDelete}
|
||||
onClose={() => {
|
||||
setUndoToast({ isVisible: false, message: '', count: 0 });
|
||||
// 不清空历史栈,允许Toast消失后仍可Ctrl+Z
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* 撤销删除 Toast 组件
|
||||
* 删除后显示撤销按钮,允许用户恢复刚删除的文件
|
||||
*/
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { RotateCcw, X } from 'lucide-react';
|
||||
|
||||
function UndoToast({ isVisible, message, onUndo, onClose, duration = 3000 }) {
|
||||
useEffect(() => {
|
||||
if (!isVisible) return;
|
||||
|
||||
// Toast出现或消息变化时启动/重置计时器
|
||||
// 文件夹切换导致的重新计时问题通过外部useEffect监听selectedFolder解决
|
||||
const timer = setTimeout(() => {
|
||||
onClose();
|
||||
}, duration);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [isVisible, message, duration, onClose]);
|
||||
|
||||
if (!isVisible) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-20 left-1/2 transform -translate-x-1/2 z-50 animate-slide-up">
|
||||
<div className="bg-gray-900 dark:bg-gray-800 text-white rounded-lg shadow-2xl px-4 py-3 flex items-center gap-4 min-w-[300px]">
|
||||
<span className="flex-1 text-sm">{message}</span>
|
||||
<button
|
||||
onClick={onUndo}
|
||||
className="flex items-center gap-1 px-3 py-1 bg-blue-600 hover:bg-blue-700 rounded transition-colors text-sm font-medium"
|
||||
>
|
||||
<RotateCcw size={14} />
|
||||
撤销
|
||||
</button>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-400 hover:text-white transition-colors"
|
||||
>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default UndoToast;
|
||||
@@ -111,3 +111,19 @@ body {
|
||||
.dark ::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(255, 255, 255, 0.25); /* 悬停时更明显 */
|
||||
}
|
||||
|
||||
/* Toast 滑入动画 */
|
||||
@keyframes slide-up {
|
||||
from {
|
||||
transform: translate(-50%, 100px);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translate(-50%, 0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.animate-slide-up {
|
||||
animation: slide-up 0.3s ease-out;
|
||||
}
|
||||
Reference in new issue
Block a user