diff --git a/backend/src/routes/file.js b/backend/src/routes/file.js
index 04d8e4f..ee6e3cb 100644
--- a/backend/src/routes/file.js
+++ b/backend/src/routes/file.js
@@ -155,4 +155,27 @@ router.post('/restore', asyncHandler(async (req, res) => {
});
}));
+/**
+ * 创建空文件夹
+ * POST /api/file/create-folder
+ * Body: { libraryId, folderPath }
+ */
+router.post('/create-folder', asyncHandler(async (req, res) => {
+ const { libraryId, folderPath } = req.body;
+
+ if (!libraryId || !folderPath) {
+ return res.status(400).json({
+ success: false,
+ error: '缺少必需参数'
+ });
+ }
+
+ const result = await fileService.createFolder(libraryId, folderPath);
+
+ res.json({
+ success: true,
+ data: result
+ });
+}));
+
module.exports = router;
diff --git a/backend/src/services/FileService.js b/backend/src/services/FileService.js
index acdd228..33bf705 100644
--- a/backend/src/services/FileService.js
+++ b/backend/src/services/FileService.js
@@ -985,6 +985,64 @@ class FileService {
db.updateLastModified();
}
+ /**
+ * 创建空文件夹
+ * @param {string} libraryId - 素材库ID
+ * @param {string} folderPath - 文件夹路径(相对路径)
+ */
+ async createFolder(libraryId, folderPath) {
+ const db = this._getDatabase(libraryId);
+ const libraryPath = db.libraryPath;
+ const fullPath = path.join(libraryPath, folderPath);
+
+ // 检查文件夹是否已存在
+ if (fs.existsSync(fullPath)) {
+ throw new Error('文件夹已存在');
+ }
+
+ // 创建文件夹
+ fs.mkdirSync(fullPath, { recursive: true });
+ console.log(`📁 创建文件夹: ${folderPath}`);
+
+ // 添加到数据库
+ const normalizedPath = folderPath.replace(/\\/g, '/');
+ const parentPath = normalizedPath.includes('/')
+ ? normalizedPath.substring(0, normalizedPath.lastIndexOf('/'))
+ : '';
+ const name = normalizedPath.split('/').pop();
+
+ // 确保父文件夹链存在
+ if (parentPath) {
+ let current = parentPath;
+ while (current && current !== '.') {
+ const existing = db.getFolderByPath(current);
+ if (!existing) {
+ const parent = path.posix.dirname(current);
+ const folderName = current.split('/').pop();
+ db.insertFolder({
+ path: current,
+ parent_path: parent === '.' ? '' : parent,
+ name: folderName,
+ image_count: 0
+ });
+ }
+ const parent = path.posix.dirname(current);
+ if (parent === current) break;
+ current = parent;
+ }
+ }
+
+ // 插入新文件夹
+ db.insertFolder({
+ path: normalizedPath,
+ parent_path: parentPath,
+ name: name,
+ image_count: 0
+ });
+
+ return { path: normalizedPath };
+ }
+
/**
* 删除缩略图(私有方法)
*/
diff --git a/frontend/src/api/file.js b/frontend/src/api/file.js
index ba5a9d4..b9f8c9c 100644
--- a/frontend/src/api/file.js
+++ b/frontend/src/api/file.js
@@ -92,5 +92,18 @@ export const fileAPI = {
items
});
return response.data;
+ },
+
+ /**
+ * 创建空文件夹
+ * @param {string} libraryId - 素材库ID
+ * @param {string} folderPath - 文件夹路径
+ */
+ async createFolder(libraryId, folderPath) {
+ const response = await axios.post(`${API_BASE}/api/file/create-folder`, {
+ libraryId,
+ folderPath
+ });
+ return response.data;
}
};
diff --git a/frontend/src/components/ContextMenu.jsx b/frontend/src/components/ContextMenu.jsx
index d86a1b3..d5389b0 100644
--- a/frontend/src/components/ContextMenu.jsx
+++ b/frontend/src/components/ContextMenu.jsx
@@ -4,7 +4,7 @@
*/
import { useEffect, useRef } from 'react';
-import { Trash2, Edit3, Move, Copy } from 'lucide-react';
+import { Trash2, Edit3, Move, Copy, FolderPlus } from 'lucide-react';
function ContextMenu({ isOpen, position, onClose, options }) {
const menuRef = useRef(null);
@@ -147,6 +147,16 @@ export const menuItems = {
shortcut: 'Ctrl+C',
action
}),
+ newSiblingFolder: (action) => ({
+ icon: ,
+ label: '新建同级文件夹',
+ action
+ }),
+ newSubFolder: (action) => ({
+ icon: ,
+ label: '新建子文件夹',
+ action
+ }),
divider: () => ({ divider: true })
};
diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx
index 7062ffd..c513eb2 100644
--- a/frontend/src/components/Sidebar.jsx
+++ b/frontend/src/components/Sidebar.jsx
@@ -54,9 +54,12 @@ function Sidebar() {
const [moveFolderPath, setMoveFolderPath] = useState(null); // 待移动的文件夹路径
const [renamingFolder, setRenamingFolder] = useState(null); // 正在重命名的文件夹
const [editingFolderName, setEditingFolderName] = useState(''); // 编辑中的文件夹名
+ const [creatingFolder, setCreatingFolder] = useState(null); // 正在创建的文件夹 { type: 'sibling' | 'child', parentPath: string }
+ const [newFolderName, setNewFolderName] = useState(''); // 新建文件夹名称
const folderSearchDebounceRef = useRef(null);
const librarySelectorRef = useRef(null);
const folderNameInputRef = useRef(null);
+ const newFolderInputRef = useRef(null);
// 文件夹搜索防抖(300ms)
const handleFolderSearchChange = (value) => {
@@ -561,6 +564,69 @@ function Sidebar() {
setEditingFolderName('');
};
+ // 开始创建文件夹
+ const handleStartCreateFolder = (type, basePath) => {
+ // type: 'sibling' 同级 | 'child' 子级
+ // basePath: 基准文件夹路径
+ const parentPath = type === 'sibling'
+ ? (basePath.includes('/') ? basePath.substring(0, basePath.lastIndexOf('/')) : '')
+ : basePath;
+
+ setCreatingFolder({ type, parentPath, basePath });
+ setNewFolderName('新建文件夹');
+ setContextMenu({ isOpen: false, position: null, folder: null });
+
+ // 延迟聚焦
+ setTimeout(() => {
+ if (newFolderInputRef.current) {
+ newFolderInputRef.current.focus();
+ newFolderInputRef.current.select();
+ }
+ }, 50);
+ };
+
+ // 完成创建文件夹
+ const handleFinishCreateFolder = async () => {
+ if (!creatingFolder || !newFolderName.trim()) {
+ setCreatingFolder(null);
+ setNewFolderName('');
+ return;
+ }
+
+ const folderName = newFolderName.trim();
+ const { parentPath } = creatingFolder;
+ const newFolderPath = parentPath ? `${parentPath}/${folderName}` : folderName;
+
+ try {
+ // 调用后端 API 创建文件夹
+ await fileAPI.createFolder(currentLibraryId, newFolderPath);
+
+ console.log(`✅ 文件夹创建成功: ${newFolderPath}`);
+
+ // 刷新文件夹列表
+ const foldersRes = await imageAPI.getFolders(currentLibraryId);
+ const { setFolders } = useImageStore.getState();
+ setFolders(foldersRes.folders);
+
+ // 展开父文件夹
+ if (parentPath) {
+ setExpandedFolders(prev => new Set([...prev, parentPath]));
+ }
+ } catch (error) {
+ console.error('创建文件夹失败:', error);
+ alert('创建文件夹失败: ' + (error.message || '未知错误'));
+ } finally {
+ setCreatingFolder(null);
+ setNewFolderName('');
+ }
+ };
+
+ // 取消创建文件夹
+ const handleCancelCreateFolder = () => {
+ setCreatingFolder(null);
+ setNewFolderName('');
+ };
+
const handleAddLibrary = async () => {
// 扫描期间禁止添加素材库
if (isScanning()) {
@@ -1021,7 +1087,66 @@ function Sidebar() {
{/* 图片数量 */}
{folder.imageCount}
+
+ {/* 新建子文件夹输入框 */}
+ {creatingFolder && creatingFolder.type === 'child' && creatingFolder.basePath === folder.path && isExpanded && (
+
+
+
+
setNewFolderName(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ handleFinishCreateFolder();
+ } else if (e.key === 'Escape') {
+ e.preventDefault();
+ handleCancelCreateFolder();
+ }
+ }}
+ onBlur={handleFinishCreateFolder}
+ onClick={(e) => e.stopPropagation()}
+ className="flex-1 text-sm text-gray-700 dark:text-gray-300 bg-transparent border-none outline-none focus:outline-none underline decoration-2 decoration-green-500 underline-offset-2"
+ />
+
+ )}
+
{hasChildren && isExpanded && renderFolderTree(folder.children, level + 1)}
+
+ {/* 新建同级文件夹输入框(在当前文件夹的子元素之后) */}
+ {creatingFolder && creatingFolder.type === 'sibling' && creatingFolder.basePath === folder.path && (
+
+
+
+
setNewFolderName(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ handleFinishCreateFolder();
+ } else if (e.key === 'Escape') {
+ e.preventDefault();
+ handleCancelCreateFolder();
+ }
+ }}
+ onBlur={handleFinishCreateFolder}
+ onClick={(e) => e.stopPropagation()}
+ className="flex-1 text-sm text-gray-700 dark:text-gray-300 bg-transparent border-none outline-none focus:outline-none underline decoration-2 decoration-green-500 underline-offset-2"
+ />
+
+ )}
);
});
@@ -1313,6 +1438,9 @@ function Sidebar() {
position={contextMenu.position}
onClose={() => setContextMenu({ isOpen: false, position: null, folder: null })}
options={contextMenu.folder ? [
+ menuItems.newSiblingFolder(() => handleStartCreateFolder('sibling', contextMenu.folder.path)),
+ menuItems.newSubFolder(() => handleStartCreateFolder('child', contextMenu.folder.path)),
+ menuItems.divider(),
menuItems.rename(() => handleStartRenameFolder(contextMenu.folder)),
menuItems.move(() => handleMoveFolderClick(contextMenu.folder.path)),
menuItems.delete(async () => {