diff --git a/backend/src/services/FileService.js b/backend/src/services/FileService.js
index d83aa3b..49851c1 100644
--- a/backend/src/services/FileService.js
+++ b/backend/src/services/FileService.js
@@ -550,36 +550,106 @@ class FileService {
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);
+ // 归一化路径(使用正斜杠)
+ const oldPath = item.path.replace(/\\/g, '/');
+ const fileName = path.basename(oldPath);
+ const normalizedTarget = targetFolder ? targetFolder.replace(/\\/g, '/') : '';
- // 检查源文件是否存在
+ // 目标文件夹相对路径
+ const newRelativeFolder = normalizedTarget
+ ? `${normalizedTarget}/${fileName}`
+ : fileName;
+
+ const oldFullPath = path.join(libraryPath, oldPath);
+ const newFullPath = path.join(libraryPath, newRelativeFolder);
+
+ // 检查源路径是否存在
if (!fs.existsSync(oldFullPath)) {
- results.failed.push({ path: item.path, error: '源文件不存在' });
+ results.failed.push({ path: oldPath, error: '源文件不存在' });
continue;
}
- // 检查目标文件夹是否存在
- const targetFullPath = path.join(libraryPath, targetFolder);
+ // 检查目标父级文件夹是否存在
+ const targetFullPath = normalizedTarget
+ ? path.join(libraryPath, normalizedTarget)
+ : libraryPath;
if (!fs.existsSync(targetFullPath)) {
fs.mkdirSync(targetFullPath, { recursive: true });
}
- // 检查目标是否已存在同名文件
+ // 检查目标是否已存在同名文件/文件夹
if (fs.existsSync(newFullPath)) {
- results.failed.push({ path: item.path, error: '目标位置已存在同名文件' });
+ results.failed.push({ path: oldPath, error: '目标位置已存在同名文件' });
continue;
}
- // 移动文件(同分区使用 rename,跨分区自动降级为复制+删除)
- fs.renameSync(oldFullPath, newFullPath);
+ if (item.type === 'folder') {
+ // ===== 文件夹移动逻辑 =====
- // 更新数据库
- const newRelativePath = path.relative(libraryPath, newFullPath).replace(/\\/g, '/');
- this._updatePathInDatabase(db, item.path, newRelativePath);
+ // 1. 先在磁盘上移动整个文件夹树
+ fs.renameSync(oldFullPath, newFullPath);
- results.success.push({ oldPath: item.path, newPath: newRelativePath });
+ // 2. 更新 folders 表中该文件夹及其所有子文件夹的 path / parent_path
+ const oldFolderPath = oldPath;
+ const newFolderPath = newRelativeFolder;
+ const len = oldFolderPath.length + 1; // 用于 substr 去掉前缀
+
+ // 2.1 更新根文件夹记录
+ const updateRootFolderStmt = db.db.prepare(`
+ UPDATE folders
+ SET path = ?, parent_path = ?
+ WHERE path = ?
+ `);
+ updateRootFolderStmt.run(
+ newFolderPath,
+ normalizedTarget || null,
+ oldFolderPath
+ );
+
+ // 2.2 更新子文件夹记录(保持层级结构)
+ const updateChildFoldersStmt = db.db.prepare(`
+ UPDATE folders
+ SET path = ? || substr(path, ?),
+ parent_path = ? || substr(parent_path, ?)
+ WHERE path LIKE ?
+ `);
+ updateChildFoldersStmt.run(
+ newFolderPath,
+ len,
+ newFolderPath,
+ len,
+ `${oldFolderPath}/%`
+ );
+
+ // 3. 更新 images 表中所有属于该文件夹及子文件夹的图片路径和 folder 字段
+ const updateImagesStmt = db.db.prepare(`
+ UPDATE images
+ SET path = ? || substr(path, ?),
+ folder = ? || substr(folder, ?)
+ WHERE folder = ? OR folder LIKE ?
+ `);
+ updateImagesStmt.run(
+ newFolderPath,
+ len,
+ newFolderPath,
+ len,
+ oldFolderPath,
+ `${oldFolderPath}/%`
+ );
+
+ results.success.push({ oldPath: oldFolderPath, newPath: newFolderPath });
+ } else {
+ // ===== 单个文件移动逻辑(保持原有行为) =====
+
+ // 移动文件(同分区使用 rename,跨分区自动降级为复制+删除)
+ fs.renameSync(oldFullPath, newFullPath);
+
+ // 更新数据库(单个图片记录)
+ const newRelativePath = newRelativeFolder.replace(/\\/g, '/');
+ this._updatePathInDatabase(db, oldPath, newRelativePath);
+
+ results.success.push({ oldPath, newPath: newRelativePath });
+ }
} catch (error) {
console.error(`移动失败 ${item.path}:`, error.message);
results.failed.push({ path: item.path, error: error.message });
diff --git a/frontend/src/components/ContextMenu.jsx b/frontend/src/components/ContextMenu.jsx
index f138d01..d86a1b3 100644
--- a/frontend/src/components/ContextMenu.jsx
+++ b/frontend/src/components/ContextMenu.jsx
@@ -36,9 +36,43 @@ function ContextMenu({ isOpen, position, onClose, options }) {
if (!isOpen || !position) return null;
// 计算菜单位置,防止超出屏幕
+ const calculateMenuPosition = () => {
+ // 估算菜单尺寸(实际渲染后会更准确)
+ const menuWidth = 200;
+ const menuHeight = options.length * 40 + 16; // 每项约40px + padding
+
+ const viewportWidth = window.innerWidth;
+ const viewportHeight = window.innerHeight;
+
+ let left = position.x;
+ let top = position.y;
+
+ // 检查右边界
+ if (left + menuWidth > viewportWidth) {
+ left = viewportWidth - menuWidth - 10; // 留10px边距
+ }
+
+ // 检查底部边界
+ if (top + menuHeight > viewportHeight) {
+ // 优先向上显示
+ top = position.y - menuHeight;
+ // 如果向上也超出,则贴底显示
+ if (top < 0) {
+ top = viewportHeight - menuHeight - 10;
+ }
+ }
+
+ // 确保不超出左边界和顶部
+ left = Math.max(10, left);
+ top = Math.max(10, top);
+
+ return { left, top };
+ };
+
+ const menuPosition = calculateMenuPosition();
const menuStyle = {
- left: `${position.x}px`,
- top: `${position.y}px`,
+ left: `${menuPosition.left}px`,
+ top: `${menuPosition.top}px`,
};
const handleOptionClick = (action) => {
diff --git a/frontend/src/components/FolderSelector.jsx b/frontend/src/components/FolderSelector.jsx
new file mode 100644
index 0000000..a6b0d84
--- /dev/null
+++ b/frontend/src/components/FolderSelector.jsx
@@ -0,0 +1,226 @@
+/**
+ * 文件夹选择器组件
+ * 用于移动/复制文件时选择目标文件夹
+ */
+
+import { useState, useMemo, useEffect, useRef } from 'react';
+import { Folder, ChevronRight, ChevronDown, X, Home } from 'lucide-react';
+
+export default function FolderSelector({ folders, currentFolder, onSelect, onClose }) {
+ const [expandedFolders, setExpandedFolders] = useState(new Set());
+ const [selectedFolder, setSelectedFolder] = useState(currentFolder || null);
+ const selectedFolderRef = useRef(null); // 用于引用选中的文件夹元素
+ const scrollContainerRef = useRef(null); // 用于引用滚动容器
+
+ // 初始化时自动展开当前文件夹的所有父级路径
+ useEffect(() => {
+ if (currentFolder && currentFolder !== '') {
+ const pathsToExpand = new Set();
+
+ // 获取所有父级路径
+ // 例如:A/B/C -> 需要展开 A 和 A/B
+ const parts = currentFolder.split('/');
+ for (let i = 0; i < parts.length - 1; i++) {
+ const parentPath = parts.slice(0, i + 1).join('/');
+ pathsToExpand.add(parentPath);
+ }
+
+ console.log(`📂 自动展开路径:`, Array.from(pathsToExpand));
+ console.log(`📍 当前选中: ${currentFolder}`);
+ setExpandedFolders(pathsToExpand);
+ }
+ }, [currentFolder]);
+
+ // 立即定位到选中的文件夹并居中显示
+ useEffect(() => {
+ if (selectedFolderRef.current && scrollContainerRef.current) {
+ // 立即执行,不等待动画
+ const element = selectedFolderRef.current;
+ const container = scrollContainerRef.current;
+
+ if (element && container) {
+ const elementRect = element.getBoundingClientRect();
+ const containerRect = container.getBoundingClientRect();
+
+ // 计算需要滚动的距离,使元素居中
+ const scrollTop = element.offsetTop - container.offsetTop - (containerRect.height / 2) + (elementRect.height / 2);
+
+ // 立即定位,不使用平滑滚动
+ container.scrollTop = scrollTop;
+
+ console.log(`📍 立即定位到选中文件夹: ${currentFolder}`);
+ }
+ }
+ }, [expandedFolders, currentFolder]);
+
+ // 切换文件夹展开/折叠
+ const toggleFolder = (folderPath) => {
+ setExpandedFolders(prev => {
+ const newSet = new Set(prev);
+ if (newSet.has(folderPath)) {
+ newSet.delete(folderPath);
+ } else {
+ newSet.add(folderPath);
+ }
+ return newSet;
+ });
+ };
+
+ // 处理文件夹点击:首次选中,再次点击展开/折叠
+ const handleFolderClick = (folder) => {
+ const hasChildren = folder.children && folder.children.length > 0;
+
+ // 如果是第一次点击(未选中),则选中
+ if (selectedFolder !== folder.path) {
+ setSelectedFolder(folder.path);
+ } else if (hasChildren) {
+ // 如果已经选中,且有子文件夹,则展开/折叠
+ toggleFolder(folder.path);
+ }
+ };
+
+ // 点击箭头图标:只展开/折叠,不选中
+ const handleToggleClick = (e, folderPath) => {
+ e.stopPropagation();
+ toggleFolder(folderPath);
+ };
+
+ // 确认选择
+ const handleConfirm = () => {
+ if (selectedFolder !== null) {
+ onSelect(selectedFolder);
+ }
+ };
+
+ // 渲染文件夹树
+ const renderFolderTree = (folders, level = 0) => {
+ return folders.map((folder) => {
+ const isExpanded = expandedFolders.has(folder.path);
+ const hasChildren = folder.children && folder.children.length > 0;
+ const isSelected = selectedFolder === folder.path;
+ const isCurrent = currentFolder === folder.path;
+ const isDisabled = isCurrent; // 禁止选择当前文件夹
+
+ return (
+
+
!isDisabled && handleFolderClick(folder)}
+ >
+ {/* 展开/折叠图标 - 独立点击区域 */}
+ {hasChildren ? (
+
handleToggleClick(e, folder.path)}
+ >
+ {isExpanded ? (
+
+ ) : (
+
+ )}
+
+ ) : (
+
+ )}
+
+ {/* 文件夹图标和名称 */}
+
+
+ {folder.name}
+
+
+ {isCurrent && (
+
(当前)
+ )}
+
+
+ {/* 子文件夹 */}
+ {hasChildren && isExpanded && (
+
{renderFolderTree(folder.children, level + 1)}
+ )}
+
+ );
+ });
+ };
+
+ return (
+
+
+ {/* 标题栏 */}
+
+
选择目标文件夹
+
+
+
+ {/* 文件夹列表 */}
+
+ {/* 根目录选项 */}
+
setSelectedFolder('')}
+ >
+
+ 根目录
+
+
+ {/* 文件夹树 */}
+ {folders && folders.length > 0 ? (
+ renderFolderTree(folders)
+ ) : (
+
+ 暂无文件夹
+
+ )}
+
+
+ {/* 底部按钮 */}
+
+
+
+
+
+
+ );
+}
diff --git a/frontend/src/components/ImageWaterfall.jsx b/frontend/src/components/ImageWaterfall.jsx
index 449c6ce..feafb8b 100644
--- a/frontend/src/components/ImageWaterfall.jsx
+++ b/frontend/src/components/ImageWaterfall.jsx
@@ -12,6 +12,7 @@ import requestManager, { RequestType } from '../services/requestManager';
import FileViewer from './FileViewer';
import ContextMenu, { menuItems } from './ContextMenu';
import UndoToast from './UndoToast';
+import FolderSelector from './FolderSelector';
// 虚拟滚动阈值:超过此数量启用虚拟滚动
const VIRTUAL_SCROLL_THRESHOLD = 100;
@@ -58,7 +59,7 @@ function ImageWaterfall() {
const {
images, selectedImage, setSelectedImage, selectedImages, setSelectedImages,
toggleImageSelection, clearSelection, imageLoadingState, selectedFolder, setSelectedFolder,
- searchKeywords, filters, appendImages, setImageLoadingState, setImages, setFolders
+ searchKeywords, filters, appendImages, setImageLoadingState, setImages, folders, setFolders
} = useImageStore();
const { thumbnailHeight, isResizingPanels } = useUIStore();
@@ -117,6 +118,8 @@ function ImageWaterfall() {
const [contextMenu, setContextMenu] = useState({ isOpen: false, position: null, image: null });
const [undoToast, setUndoToast] = useState({ isVisible: false, message: '', count: 0 });
const [undoHistory, setUndoHistory] = useState([]); // 撤销历史栈,支持多次撤销
+ const [showFolderSelector, setShowFolderSelector] = useState(false); // 显示文件夹选择器
+ const [moveItems, setMoveItems] = useState([]); // 待移动的项
// 监听文件夹切换,切换时关闭Toast
useEffect(() => {
@@ -629,15 +632,71 @@ function ImageWaterfall() {
});
};
+ // 打开移动文件夹选择器
+ const handleMoveClick = useCallback(() => {
+ // 准备待移动的项
+ const itemsToMove = selectedImages.length > 0
+ ? selectedImages.map(img => ({ type: 'file', path: img.path }))
+ : selectedImage
+ ? [{ type: 'file', path: selectedImage.path }]
+ : [];
+
+ if (itemsToMove.length === 0) return;
+
+ setMoveItems(itemsToMove);
+ setShowFolderSelector(true);
+ setContextMenu({ isOpen: false, position: null, image: null });
+ }, [selectedImages, selectedImage]);
+
+ // 执行移动
+ const handleMove = useCallback(async (targetFolder) => {
+ if (!currentLibraryId || moveItems.length === 0) return;
+
+ setShowFolderSelector(false);
+
+ // 1. 立即从当前列表中移除这些图片(乐观更新)
+ const movedPaths = new Set(moveItems.map(item => item.path));
+ const remainingImages = images.filter(img => !movedPaths.has(img.path));
+ setImages(remainingImages);
+ clearSelection();
+
+ try {
+ // 2. 后台执行移动和刷新(并行)
+ const [result, foldersRes] = await Promise.all([
+ fileAPI.move(currentLibraryId, moveItems, targetFolder),
+ imageAPI.getFolders(currentLibraryId)
+ ]);
+
+ if (result.failed && result.failed.length > 0) {
+ alert(`移动失败: ${result.failed[0].error}`);
+ // 失败时恢复图片列表
+ setImages(images);
+ } else {
+ console.log(`✅ 已移动 ${moveItems.length} 个文件到: ${targetFolder || '根目录'}`);
+ }
+
+ // 3. 刷新文件夹列表
+ setFolders(foldersRes.folders);
+ } catch (error) {
+ console.error('移动失败:', error);
+ alert('移动失败: ' + (error.message || '未知错误'));
+ // 失败时恢复图片列表
+ setImages(images);
+ } finally {
+ setMoveItems([]);
+ }
+ }, [currentLibraryId, moveItems, images, setImages, clearSelection, setFolders]);
+
// 准备右键菜单选项
const getContextMenuOptions = useCallback((image) => {
return [
+ menuItems.move(handleMoveClick),
menuItems.delete(async () => {
setContextMenu({ isOpen: false, position: null, image: null });
await handleQuickDelete();
})
];
- }, [selectedImages, selectedImage]);
+ }, [selectedImages, selectedImage, handleMoveClick]);
// 渲染单个图片单元格
const renderImageCell = (image, flatIndex) => {
@@ -672,10 +731,18 @@ function ImageWaterfall() {
onContextMenu={(e) => handleContextMenu(e, image)}
draggable={true}
onDragStart={(e) => {
- const items = selectedImages.length > 0 && selectedImages.some(img => img.id === image.id)
+ // 准备拖拽的图片列表
+ const draggedImages = selectedImages.length > 0 && selectedImages.some(img => img.id === image.id)
? selectedImages
: [image];
- e.dataTransfer.setData('flypic/images', JSON.stringify(items));
+
+ // 转换为 items 格式(type + path)
+ const items = draggedImages.map(img => ({
+ type: 'file',
+ path: img.path
+ }));
+
+ e.dataTransfer.setData('application/json', JSON.stringify({ items }));
e.dataTransfer.effectAllowed = 'move';
}}
>
@@ -862,6 +929,19 @@ function ImageWaterfall() {
// 不清空历史栈,允许Toast消失后仍可Ctrl+Z
}}
/>
+
+ {/* 文件夹选择器 */}
+ {showFolderSelector && (
+ {
+ setShowFolderSelector(false);
+ setMoveItems([]);
+ }}
+ />
+ )}
);
}
diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx
index 830f34a..b68e2b3 100644
--- a/frontend/src/components/Sidebar.jsx
+++ b/frontend/src/components/Sidebar.jsx
@@ -9,6 +9,7 @@ import { onUserActionStart } from '../services/imageLoadService';
import LibraryMissingModal from './LibraryMissingModal';
import ContextMenu, { menuItems } from './ContextMenu';
import UndoToast from './UndoToast';
+import FolderSelector from './FolderSelector';
// 检查素材库扫描状态
const checkScanStatus = async (libraryId) => {
@@ -48,6 +49,9 @@ function Sidebar() {
const [contextMenu, setContextMenu] = useState({ isOpen: false, position: null, folder: null });
const [undoToast, setUndoToast] = useState({ isVisible: false, message: '', count: 0 });
const [undoHistory, setUndoHistory] = useState([]); // 撤销历史栈,支持多次撤销
+ const [dragOverFolder, setDragOverFolder] = useState(null); // 拖拽悬停的文件夹
+ const [showFolderSelector, setShowFolderSelector] = useState(false); // 显示文件夹选择器
+ const [moveFolderPath, setMoveFolderPath] = useState(null); // 待移动的文件夹路径
const folderSearchDebounceRef = useRef(null);
const librarySelectorRef = useRef(null);
@@ -331,6 +335,114 @@ function Sidebar() {
});
};
+ // 处理拖拽到文件夹
+ const handleDrop = async (e, targetFolder) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setDragOverFolder(null);
+
+ if (!currentLibraryId) return;
+
+ try {
+ const data = JSON.parse(e.dataTransfer.getData('application/json'));
+ const { items } = data;
+
+ if (!items || items.length === 0) return;
+
+ // 检查是否包含文件夹
+ const hasFolders = items.some(item => item.type === 'folder');
+
+ // 1. 如果是移动文件,立即从UI中移除(乐观更新)
+ if (!hasFolders) {
+ const { images, setImages } = useImageStore.getState();
+ const movedPaths = new Set(items.map(item => item.path));
+ const remainingImages = images.filter(img => !movedPaths.has(img.path));
+ setImages(remainingImages);
+ }
+
+ // 2. 执行移动和刷新(并行)
+ const [result, foldersRes] = await Promise.all([
+ fileAPI.move(currentLibraryId, items, targetFolder.path),
+ imageAPI.getFolders(currentLibraryId)
+ ]);
+
+ if (result.failed && result.failed.length > 0) {
+ alert(`移动失败: ${result.failed[0].error}`);
+ } else {
+ console.log(`✅ 已移动 ${items.length} 个${hasFolders ? '文件夹' : '文件'}到: ${targetFolder.path}`);
+ }
+
+ // 3. 刷新文件夹列表
+ const { setFolders } = useImageStore.getState();
+ setFolders(foldersRes.folders);
+ } catch (error) {
+ console.error('拖拽移动失败:', error);
+ }
+ };
+
+ const handleDragOver = (e, folder) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setDragOverFolder(folder.path);
+ };
+
+ const handleDragLeave = (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setDragOverFolder(null);
+ };
+
+ // 打开文件夹移动选择器
+ const handleMoveFolderClick = (folderPath) => {
+ setMoveFolderPath(folderPath);
+ setShowFolderSelector(true);
+ setContextMenu({ isOpen: false, position: null, folder: null });
+ };
+
+ // 执行文件夹移动
+ const handleMoveFolder = async (targetFolder) => {
+ if (!currentLibraryId || !moveFolderPath) return;
+
+ setShowFolderSelector(false);
+
+ // 计算移动后的新路径
+ const folderName = moveFolderPath.split('/').pop();
+ const newPath = targetFolder ? `${targetFolder}/${folderName}` : folderName;
+
+ try {
+ const items = [{ type: 'folder', path: moveFolderPath }];
+
+ // 1. 后台执行移动和刷新(并行)
+ const [result, foldersRes] = await Promise.all([
+ fileAPI.move(currentLibraryId, items, targetFolder),
+ imageAPI.getFolders(currentLibraryId)
+ ]);
+
+ if (result.failed && result.failed.length > 0) {
+ alert(`移动失败: ${result.failed[0].error}`);
+ } else {
+ // 2. 移动成功,选中新位置
+ setSelectedFolder(newPath);
+ console.log(`✅ 已移动文件夹: ${moveFolderPath} -> ${newPath}`);
+ }
+
+ // 3. 刷新文件夹列表
+ const { setFolders } = useImageStore.getState();
+ setFolders(foldersRes.folders);
+ } catch (error) {
+ console.error('移动文件夹失败:', error);
+ alert('移动失败: ' + (error.message || '未知错误'));
+
+ // 失败时重新加载文件夹列表
+ imageAPI.getFolders(currentLibraryId).then(foldersRes => {
+ const { setFolders } = useImageStore.getState();
+ setFolders(foldersRes.folders);
+ });
+ } finally {
+ setMoveFolderPath(null);
+ }
+ };
+
const handleAddLibrary = async () => {
// 扫描期间禁止添加素材库
if (isScanning()) {
@@ -712,10 +824,13 @@ function Sidebar() {
return (
handleFolderClick(folder)}
onContextMenu={(e) => {
@@ -726,6 +841,16 @@ function Sidebar() {
folder: folder
});
}}
+ draggable={true}
+ onDragStart={(e) => {
+ // 拖拽文件夹
+ const items = [{ type: 'folder', path: folder.path }];
+ e.dataTransfer.setData('application/json', JSON.stringify({ items }));
+ e.dataTransfer.effectAllowed = 'move';
+ }}
+ onDrop={(e) => handleDrop(e, folder)}
+ onDragOver={(e) => handleDragOver(e, folder)}
+ onDragLeave={handleDragLeave}
>
{/* 展开/折叠图标 - 独立点击区域 */}
{hasChildren ? (
@@ -1046,6 +1171,7 @@ function Sidebar() {
position={contextMenu.position}
onClose={() => setContextMenu({ isOpen: false, position: null, folder: null })}
options={contextMenu.folder ? [
+ menuItems.move(() => handleMoveFolderClick(contextMenu.folder.path)),
menuItems.delete(async () => {
setContextMenu({ isOpen: false, position: null, folder: null });
await handleDeleteFolder(contextMenu.folder.path);
@@ -1063,6 +1189,19 @@ function Sidebar() {
// 不清空历史栈,允许Toast消失后仍可Ctrl+Z
}}
/>
+
+ {/* 文件夹选择器 */}
+ {showFolderSelector && (
+ {
+ setShowFolderSelector(false);
+ setMoveFolderPath(null);
+ }}
+ />
+ )}
);
}