新增 文件操作 重命名
This commit is contained in:
1 parent
2d349d1d73
commit
7ef71ac6e1
5 files changed
+504
-55
No files matched your search
@@ -509,53 +509,64 @@ class FileService {
|
||||
/**
|
||||
* 重命名文件或文件夹
|
||||
* @param {string} libraryId - 素材库ID
|
||||
* @param {string} oldPath - 旧路径(相对路径)
|
||||
* @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);
|
||||
// 归一化旧路径,确保使用正斜杠
|
||||
const normalizedOldPath = oldPath.replace(/\\/g, '/');
|
||||
const fullOldPath = path.join(libraryPath, normalizedOldPath);
|
||||
|
||||
// 检查文件是否存在
|
||||
// 检查文件/文件夹是否存在
|
||||
if (!fs.existsSync(fullOldPath)) {
|
||||
throw new Error('文件不存在');
|
||||
}
|
||||
|
||||
// 检查新名称是否已存在
|
||||
if (fs.existsSync(fullNewPath)) {
|
||||
// 自动添加编号
|
||||
const ext = path.extname(newName);
|
||||
const basename = path.basename(newName, ext);
|
||||
const stat = fs.lstatSync(fullOldPath);
|
||||
const isDirectory = stat.isDirectory();
|
||||
|
||||
const directory = path.dirname(fullOldPath);
|
||||
const initialNewPath = path.join(directory, newName);
|
||||
|
||||
// 如果目标已存在,则自动编号避免冲突
|
||||
let finalFullNewPath = initialNewPath;
|
||||
let finalNewName = newName;
|
||||
|
||||
if (fs.existsSync(finalFullNewPath)) {
|
||||
const ext = isDirectory ? '' : path.extname(newName);
|
||||
const basename = isDirectory ? newName : path.basename(newName, ext);
|
||||
let counter = 1;
|
||||
let finalNewPath = fullNewPath;
|
||||
|
||||
while (fs.existsSync(finalNewPath)) {
|
||||
const numberedName = `${basename} (${counter})${ext}`;
|
||||
finalNewPath = path.join(directory, numberedName);
|
||||
|
||||
while (fs.existsSync(finalFullNewPath)) {
|
||||
const numberedName = isDirectory
|
||||
? `${basename} (${counter})`
|
||||
: `${basename} (${counter})${ext}`;
|
||||
finalFullNewPath = path.join(directory, numberedName);
|
||||
finalNewName = 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);
|
||||
// 执行重命名(文件或文件夹)
|
||||
fs.renameSync(fullOldPath, finalFullNewPath);
|
||||
|
||||
// 更新数据库
|
||||
const newRelativePath = path.relative(libraryPath, fullNewPath).replace(/\\/g, '/');
|
||||
this._updatePathInDatabase(db, oldPath, newRelativePath);
|
||||
// 计算新的相对路径
|
||||
const newRelativePath = path
|
||||
.relative(libraryPath, finalFullNewPath)
|
||||
.replace(/\\/g, '/');
|
||||
|
||||
return { newPath: newRelativePath, newName };
|
||||
if (isDirectory) {
|
||||
// 文件夹:更新 folders 表与 images 表中所有相关记录
|
||||
this._updateFolderPathInDatabase(db, normalizedOldPath, newRelativePath);
|
||||
} else {
|
||||
// 单个文件:仅更新 images 表中的一条记录
|
||||
this._updatePathInDatabase(db, normalizedOldPath, newRelativePath);
|
||||
}
|
||||
|
||||
return { newPath: newRelativePath, newName: finalNewName };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -795,13 +806,15 @@ class FileService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新数据库中的路径(私有方法)
|
||||
* 更新数据库中的路径(仅用于单个文件)
|
||||
* @private
|
||||
*/
|
||||
_updatePathInDatabase(db, oldPath, newPath) {
|
||||
const image = db.getImageByPath(oldPath);
|
||||
if (!image) return;
|
||||
if (!image) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 更新路径和文件名
|
||||
const newFilename = path.basename(newPath);
|
||||
const newFolder = path.dirname(newPath);
|
||||
|
||||
@@ -821,6 +834,68 @@ class FileService {
|
||||
db.updateLastModified();
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新数据库中的文件夹路径(folders + images)
|
||||
* @private
|
||||
*/
|
||||
_updateFolderPathInDatabase(db, oldFolderPath, newFolderPath) {
|
||||
const normalizedOld = oldFolderPath.replace(/\\/g, '/');
|
||||
const normalizedNew = newFolderPath.replace(/\\/g, '/');
|
||||
|
||||
const len = normalizedOld.length + 1; // 用于去掉前缀
|
||||
|
||||
// 1. 更新根文件夹记录(path / name,parent_path 保持不变)
|
||||
const rootFolder = db.getFolderByPath(normalizedOld);
|
||||
const parentPath = rootFolder ? rootFolder.parent_path : path.dirname(normalizedOld);
|
||||
|
||||
const updateRootFolderStmt = db.db.prepare(`
|
||||
UPDATE folders
|
||||
SET path = ?, parent_path = ?, name = ?
|
||||
WHERE path = ?
|
||||
`);
|
||||
updateRootFolderStmt.run(
|
||||
normalizedNew,
|
||||
parentPath || null,
|
||||
path.basename(normalizedNew),
|
||||
normalizedOld
|
||||
);
|
||||
|
||||
// 2. 更新子文件夹记录(保持层级结构)
|
||||
const updateChildFoldersStmt = db.db.prepare(`
|
||||
UPDATE folders
|
||||
SET path = ? || substr(path, ?),
|
||||
parent_path = ? || substr(parent_path, ?)
|
||||
WHERE path LIKE ?
|
||||
`);
|
||||
updateChildFoldersStmt.run(
|
||||
normalizedNew,
|
||||
len,
|
||||
normalizedNew,
|
||||
len,
|
||||
`${normalizedOld}/%`
|
||||
);
|
||||
|
||||
// 3. 更新 images 表中所有属于该文件夹及子文件夹的图片路径和 folder 字段
|
||||
const updateImagesStmt = db.db.prepare(`
|
||||
UPDATE images
|
||||
SET path = ? || substr(path, ?),
|
||||
folder = ? || substr(folder, ?)
|
||||
WHERE folder = ? OR folder LIKE ?
|
||||
`);
|
||||
updateImagesStmt.run(
|
||||
normalizedNew,
|
||||
len,
|
||||
normalizedNew,
|
||||
len,
|
||||
normalizedOld,
|
||||
`${normalizedOld}/%`
|
||||
);
|
||||
|
||||
// 4. 重新计算所有文件夹的图片数量
|
||||
db.updateAllFolderCounts();
|
||||
db.updateLastModified();
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除缩略图(私有方法)
|
||||
*/
|
||||
|
||||
@@ -59,7 +59,8 @@ function ImageWaterfall() {
|
||||
const {
|
||||
images, selectedImage, setSelectedImage, selectedImages, setSelectedImages,
|
||||
toggleImageSelection, clearSelection, imageLoadingState, selectedFolder, setSelectedFolder,
|
||||
searchKeywords, filters, appendImages, setImageLoadingState, setImages, folders, setFolders
|
||||
searchKeywords, filters, appendImages, setImageLoadingState, setImages, folders, setFolders,
|
||||
renamingImage, setRenamingImage, updateImage
|
||||
} = useImageStore();
|
||||
|
||||
const { thumbnailHeight, isResizingPanels } = useUIStore();
|
||||
@@ -120,6 +121,8 @@ function ImageWaterfall() {
|
||||
const [undoHistory, setUndoHistory] = useState([]); // 撤销历史栈,支持多次撤销
|
||||
const [showFolderSelector, setShowFolderSelector] = useState(false); // 显示文件夹选择器
|
||||
const [moveItems, setMoveItems] = useState([]); // 待移动的项
|
||||
const [editingFilename, setEditingFilename] = useState(''); // 编辑中的文件名
|
||||
const editInputRef = useRef(null); // 编辑输入框引用
|
||||
|
||||
// 监听文件夹切换,切换时关闭Toast
|
||||
useEffect(() => {
|
||||
@@ -127,7 +130,7 @@ function ImageWaterfall() {
|
||||
setUndoToast({ isVisible: false, message: '', count: 0 });
|
||||
}, [selectedFolder]);
|
||||
|
||||
// 全局快捷键监听 - Del 键删除, Ctrl+Z 撤销
|
||||
// 全局快捷键监听 - Del 键删除, Ctrl+Z 撤销, F2/Enter 重命名
|
||||
useEffect(() => {
|
||||
const handleGlobalKeyDown = async (e) => {
|
||||
// 忽略输入框中的快捷键
|
||||
@@ -142,6 +145,13 @@ function ImageWaterfall() {
|
||||
return;
|
||||
}
|
||||
|
||||
// F2 或 Enter → 重命名(仅单选时)
|
||||
if ((e.key === 'F2' || e.key === 'Enter') && selectedImage && selectedImages.length === 0) {
|
||||
e.preventDefault();
|
||||
handleStartRename(selectedImage);
|
||||
return;
|
||||
}
|
||||
|
||||
// Del 键 → 直接移入回收站
|
||||
if (e.key === 'Delete') {
|
||||
if (selectedImages.length > 0 || selectedImage) {
|
||||
@@ -687,16 +697,94 @@ function ImageWaterfall() {
|
||||
}
|
||||
}, [currentLibraryId, moveItems, images, setImages, clearSelection, setFolders]);
|
||||
|
||||
// 开始重命名
|
||||
const handleStartRename = useCallback((image) => {
|
||||
if (!image) return;
|
||||
setRenamingImage(image);
|
||||
// 获取不带扩展名的文件名
|
||||
const nameWithoutExt = image.filename.substring(0, image.filename.lastIndexOf('.')) || image.filename;
|
||||
setEditingFilename(nameWithoutExt);
|
||||
// 延迟聚焦,确保输入框已渲染
|
||||
setTimeout(() => {
|
||||
if (editInputRef.current) {
|
||||
editInputRef.current.focus();
|
||||
editInputRef.current.select();
|
||||
}
|
||||
}, 50);
|
||||
}, [setRenamingImage]);
|
||||
|
||||
// 完成重命名
|
||||
const handleFinishRename = useCallback(async () => {
|
||||
if (!renamingImage || !editingFilename.trim()) {
|
||||
setRenamingImage(null);
|
||||
setEditingFilename('');
|
||||
return;
|
||||
}
|
||||
|
||||
const oldFilename = renamingImage.filename;
|
||||
const ext = oldFilename.substring(oldFilename.lastIndexOf('.'));
|
||||
const newFilename = editingFilename.trim() + ext;
|
||||
|
||||
// 如果文件名没有改变,直接退出
|
||||
if (newFilename === oldFilename) {
|
||||
setRenamingImage(null);
|
||||
setEditingFilename('');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 调用重命名API
|
||||
const result = await fileAPI.rename(currentLibraryId, renamingImage.path, newFilename);
|
||||
|
||||
// 更新图片信息
|
||||
const newPath = result.data.newPath;
|
||||
const actualNewName = result.data.newName;
|
||||
updateImage(renamingImage.path, {
|
||||
path: newPath,
|
||||
filename: actualNewName
|
||||
});
|
||||
|
||||
console.log(`✅ 重命名成功: ${oldFilename} → ${actualNewName}`);
|
||||
} catch (error) {
|
||||
console.error('重命名失败:', error);
|
||||
alert('重命名失败: ' + (error.message || '未知错误'));
|
||||
} finally {
|
||||
setRenamingImage(null);
|
||||
setEditingFilename('');
|
||||
}
|
||||
}, [renamingImage, editingFilename, currentLibraryId, updateImage]);
|
||||
|
||||
// 取消重命名
|
||||
const handleCancelRename = useCallback(() => {
|
||||
setRenamingImage(null);
|
||||
setEditingFilename('');
|
||||
}, []);
|
||||
|
||||
// 准备右键菜单选项
|
||||
const getContextMenuOptions = useCallback((image) => {
|
||||
return [
|
||||
const isMultiSelection = selectedImages.length > 0;
|
||||
const menuOptions = [];
|
||||
|
||||
// 只在单选时显示重命名选项
|
||||
if (!isMultiSelection) {
|
||||
menuOptions.push(
|
||||
menuItems.rename(() => {
|
||||
setContextMenu({ isOpen: false, position: null, image: null });
|
||||
handleStartRename(image);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
menuOptions.push(
|
||||
menuItems.move(handleMoveClick),
|
||||
menuItems.delete(async () => {
|
||||
setContextMenu({ isOpen: false, position: null, image: null });
|
||||
await handleQuickDelete();
|
||||
})
|
||||
];
|
||||
}, [selectedImages, selectedImage, handleMoveClick]);
|
||||
);
|
||||
|
||||
return menuOptions;
|
||||
}, [selectedImages, selectedImage, handleMoveClick, handleStartRename]);
|
||||
|
||||
// 渲染单个图片单元格
|
||||
const renderImageCell = (image, flatIndex) => {
|
||||
@@ -780,16 +868,55 @@ function ImageWaterfall() {
|
||||
|
||||
<div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-all pointer-events-none" />
|
||||
</div>
|
||||
<div className="mt-1 px-1">
|
||||
<p
|
||||
className="text-xs truncate text-center transition-colors"
|
||||
style={{
|
||||
color: isSelected ? '#3b82f6' : '#909090',
|
||||
fontWeight: isSelected ? '600' : '400'
|
||||
}}
|
||||
>
|
||||
{image.filename}
|
||||
</p>
|
||||
<div className="mt-1 px-1 h-4 flex items-center">
|
||||
{renamingImage?.id === image.id ? (
|
||||
// 编辑模式 - 保持与显示模式相同的样式,只添加下划线提示
|
||||
<input
|
||||
ref={editInputRef}
|
||||
type="text"
|
||||
value={editingFilename}
|
||||
onChange={(e) => setEditingFilename(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
handleFinishRename();
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
handleCancelRename();
|
||||
}
|
||||
}}
|
||||
onBlur={handleFinishRename}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="w-full text-xs text-center bg-transparent border-none outline-none focus:outline-none underline decoration-2 decoration-blue-500 underline-offset-2 truncate leading-none"
|
||||
style={{
|
||||
color: isSelected ? '#3b82f6' : '#909090',
|
||||
fontWeight: isSelected ? '600' : '400',
|
||||
padding: 0,
|
||||
margin: 0,
|
||||
height: '1rem'
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
// 显示模式
|
||||
<p
|
||||
className="text-xs truncate text-center transition-colors cursor-text m-0 leading-none"
|
||||
style={{
|
||||
color: isSelected ? '#3b82f6' : '#909090',
|
||||
fontWeight: isSelected ? '600' : '400',
|
||||
height: '1rem'
|
||||
}}
|
||||
onDoubleClick={(e) => {
|
||||
// 只在单选时允许双击重命名
|
||||
if (selectedImages.length === 0) {
|
||||
e.stopPropagation();
|
||||
handleStartRename(image);
|
||||
}
|
||||
}}
|
||||
title={selectedImages.length === 0 ? "双击重命名" : ""}
|
||||
>
|
||||
{image.filename}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { Copy, Download, Check, FolderDown, ArrowLeft } from 'lucide-react';
|
||||
import { useLibraryStore } from '../stores/useLibraryStore';
|
||||
import { useImageStore } from '../stores/useImageStore';
|
||||
@@ -9,7 +9,7 @@ import JSZip from 'jszip';
|
||||
|
||||
function RightPanel() {
|
||||
const { currentLibraryId } = useLibraryStore();
|
||||
const { selectedImage, selectedImages, selectedFolder, images, setSelectedImage } = useImageStore();
|
||||
const { selectedImage, selectedImages, selectedFolder, images, setSelectedImage, updateImage } = useImageStore();
|
||||
const { setMobileView, isResizingPanels, resizingSide } = useUIStore();
|
||||
const [isMobile, setIsMobile] = useState(false);
|
||||
const [imageUrl, setImageUrl] = useState(''); // 当前显示的图片URL
|
||||
@@ -20,6 +20,9 @@ function RightPanel() {
|
||||
const [isExportingFolder, setIsExportingFolder] = useState(false);
|
||||
const [folderExportProgress, setFolderExportProgress] = useState(0);
|
||||
const [pathCopied, setPathCopied] = useState(false);
|
||||
const [isEditingFilename, setIsEditingFilename] = useState(false);
|
||||
const [editingFilename, setEditingFilename] = useState('');
|
||||
const filenameInputRef = useRef(null);
|
||||
|
||||
// 计算实际选中的图片数量(合并 selectedImage 和 selectedImages)
|
||||
const actualSelectedCount = (() => {
|
||||
@@ -117,6 +120,64 @@ function RightPanel() {
|
||||
}
|
||||
};
|
||||
|
||||
// 开始重命名
|
||||
const handleStartRename = () => {
|
||||
if (!selectedImage || isMultiSelect) return;
|
||||
const nameWithoutExt = selectedImage.filename.substring(0, selectedImage.filename.lastIndexOf('.')) || selectedImage.filename;
|
||||
setEditingFilename(nameWithoutExt);
|
||||
setIsEditingFilename(true);
|
||||
setTimeout(() => {
|
||||
if (filenameInputRef.current) {
|
||||
filenameInputRef.current.focus();
|
||||
filenameInputRef.current.select();
|
||||
}
|
||||
}, 50);
|
||||
};
|
||||
|
||||
// 完成重命名
|
||||
const handleFinishRename = async () => {
|
||||
if (!selectedImage || !editingFilename.trim()) {
|
||||
setIsEditingFilename(false);
|
||||
setEditingFilename('');
|
||||
return;
|
||||
}
|
||||
|
||||
const oldFilename = selectedImage.filename;
|
||||
const ext = oldFilename.substring(oldFilename.lastIndexOf('.'));
|
||||
const newFilename = editingFilename.trim() + ext;
|
||||
|
||||
if (newFilename === oldFilename) {
|
||||
setIsEditingFilename(false);
|
||||
setEditingFilename('');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await fileAPI.rename(currentLibraryId, selectedImage.path, newFilename);
|
||||
const newPath = result.data.newPath;
|
||||
const actualNewName = result.data.newName;
|
||||
|
||||
updateImage(selectedImage.path, {
|
||||
path: newPath,
|
||||
filename: actualNewName
|
||||
});
|
||||
|
||||
console.log(`✅ 重命名成功: ${oldFilename} → ${actualNewName}`);
|
||||
} catch (error) {
|
||||
console.error('重命名失败:', error);
|
||||
alert('重命名失败: ' + (error.message || '未知错误'));
|
||||
} finally {
|
||||
setIsEditingFilename(false);
|
||||
setEditingFilename('');
|
||||
}
|
||||
};
|
||||
|
||||
// 取消重命名
|
||||
const handleCancelRename = () => {
|
||||
setIsEditingFilename(false);
|
||||
setEditingFilename('');
|
||||
};
|
||||
|
||||
// 检测移动端
|
||||
useEffect(() => {
|
||||
const checkMobile = () => {
|
||||
@@ -935,7 +996,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>
|
||||
{isEditingFilename ? (
|
||||
<input
|
||||
ref={filenameInputRef}
|
||||
type="text"
|
||||
value={editingFilename}
|
||||
onChange={(e) => setEditingFilename(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
handleFinishRename();
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
handleCancelRename();
|
||||
}
|
||||
}}
|
||||
onBlur={handleFinishRename}
|
||||
className="w-full text-gray-900 dark:text-gray-100 bg-transparent border-none outline-none focus:outline-none break-all underline decoration-2 decoration-blue-500 underline-offset-2"
|
||||
style={{ padding: 0, margin: 0 }}
|
||||
/>
|
||||
) : (
|
||||
<p
|
||||
className="text-gray-900 dark:text-gray-100 break-all cursor-pointer hover:text-blue-500 transition-colors"
|
||||
onClick={handleStartRename}
|
||||
title="点击编辑文件名"
|
||||
>
|
||||
{selectedImage.filename}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-gray-500 dark:text-gray-400">尺寸:</span>
|
||||
|
||||
@@ -52,8 +52,11 @@ function Sidebar() {
|
||||
const [dragOverFolder, setDragOverFolder] = useState(null); // 拖拽悬停的文件夹
|
||||
const [showFolderSelector, setShowFolderSelector] = useState(false); // 显示文件夹选择器
|
||||
const [moveFolderPath, setMoveFolderPath] = useState(null); // 待移动的文件夹路径
|
||||
const [renamingFolder, setRenamingFolder] = useState(null); // 正在重命名的文件夹
|
||||
const [editingFolderName, setEditingFolderName] = useState(''); // 编辑中的文件夹名
|
||||
const folderSearchDebounceRef = useRef(null);
|
||||
const librarySelectorRef = useRef(null);
|
||||
const folderNameInputRef = useRef(null);
|
||||
|
||||
// 文件夹搜索防抖(300ms)
|
||||
const handleFolderSearchChange = (value) => {
|
||||
@@ -181,7 +184,7 @@ function Sidebar() {
|
||||
return parentPath || null;
|
||||
}, []);
|
||||
|
||||
// 监听Del键删除选中的文件夹
|
||||
// 监听快捷键(Del删除、F2重命名、Ctrl+Z撤销)
|
||||
useEffect(() => {
|
||||
const handleKeyDown = async (e) => {
|
||||
// 忽略输入框中的快捷键
|
||||
@@ -197,6 +200,40 @@ function Sidebar() {
|
||||
await handleDeleteFolder(selectedFolder);
|
||||
}
|
||||
|
||||
// F2 键 → 重命名当前选中的文件夹(只在没有选中图片时)
|
||||
if (e.key === 'F2' && selectedFolder) {
|
||||
const { selectedImages, selectedImage } = useImageStore.getState();
|
||||
// 如果有选中的图片,让 ImageWaterfall 处理重命名
|
||||
if (selectedImages.length > 0 || selectedImage) return;
|
||||
|
||||
e.preventDefault();
|
||||
// 找到对应的文件夹对象
|
||||
const findFolderByPath = (foldersList, path) => {
|
||||
for (const folder of foldersList) {
|
||||
if (folder.path === path) return folder;
|
||||
if (folder.children) {
|
||||
const found = findFolderByPath(folder.children, path);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
const folderObj = findFolderByPath(folders, selectedFolder);
|
||||
if (folderObj) {
|
||||
// 直接调用重命名逻辑,不依赖外部函数
|
||||
setRenamingFolder(folderObj);
|
||||
setEditingFolderName(folderObj.name);
|
||||
setContextMenu({ isOpen: false, position: null, folder: null });
|
||||
|
||||
setTimeout(() => {
|
||||
if (folderNameInputRef.current) {
|
||||
folderNameInputRef.current.focus();
|
||||
folderNameInputRef.current.select();
|
||||
}
|
||||
}, 50);
|
||||
}
|
||||
}
|
||||
|
||||
// Ctrl+Z → 撤销(文件夹或图片)
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 'z') {
|
||||
// 如果有文件夹撤销历史,撤销文件夹
|
||||
@@ -210,7 +247,7 @@ function Sidebar() {
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [selectedFolder, undoHistory, findNextFolderAfterDelete]);
|
||||
}, [selectedFolder, undoHistory, folders, findNextFolderAfterDelete]);
|
||||
|
||||
// 文件夹删除功能(乐观更新,立即响应)
|
||||
const handleDeleteFolder = async (folderPath) => {
|
||||
@@ -443,6 +480,87 @@ function Sidebar() {
|
||||
}
|
||||
};
|
||||
|
||||
// 开始重命名文件夹
|
||||
const handleStartRenameFolder = (folder) => {
|
||||
if (!folder) return;
|
||||
setRenamingFolder(folder);
|
||||
setEditingFolderName(folder.name);
|
||||
setContextMenu({ isOpen: false, position: null, folder: null });
|
||||
|
||||
// 延迟聚焦,确保输入框已渲染
|
||||
setTimeout(() => {
|
||||
if (folderNameInputRef.current) {
|
||||
folderNameInputRef.current.focus();
|
||||
folderNameInputRef.current.select();
|
||||
}
|
||||
}, 50);
|
||||
};
|
||||
|
||||
// 完成文件夹重命名
|
||||
const handleFinishRenameFolder = async () => {
|
||||
if (!renamingFolder || !editingFolderName.trim()) {
|
||||
setRenamingFolder(null);
|
||||
setEditingFolderName('');
|
||||
return;
|
||||
}
|
||||
|
||||
const oldName = renamingFolder.name;
|
||||
const newName = editingFolderName.trim();
|
||||
|
||||
// 如果名称没有改变,直接退出
|
||||
if (newName === oldName) {
|
||||
setRenamingFolder(null);
|
||||
setEditingFolderName('');
|
||||
return;
|
||||
}
|
||||
|
||||
const oldPath = renamingFolder.path;
|
||||
const isRenamingCurrentFolder = selectedFolder === oldPath;
|
||||
|
||||
try {
|
||||
// 调用重命名API
|
||||
const result = await fileAPI.rename(currentLibraryId, oldPath, newName);
|
||||
const newPath = result.data.newPath;
|
||||
|
||||
console.log(`✅ 文件夹重命名成功: ${oldName} → ${newName}, 路径: ${oldPath} → ${newPath}`);
|
||||
|
||||
// 1. 立即清空图片列表(避免显示旧路径的无效图片)
|
||||
const { setImages, setFolders, setSelectedFolder: setSelectedFolderGlobal } = useImageStore.getState();
|
||||
setImages([]);
|
||||
|
||||
// 2. 重新加载文件夹列表(关键:确保浏览器重新渲染)
|
||||
const foldersRes = await imageAPI.getFolders(currentLibraryId);
|
||||
console.log('📁 重命名后最新文件夹列表:', foldersRes.folders);
|
||||
setFolders(foldersRes.folders);
|
||||
|
||||
// 3. 如果重命名的是当前选中的文件夹,强制触发重新加载
|
||||
if (isRenamingCurrentFolder) {
|
||||
console.log(`📂 重命名当前文件夹: ${oldPath} → ${newPath}`);
|
||||
|
||||
// 先切换到 null,再切换到新路径,强制触发 useEffect
|
||||
setSelectedFolderGlobal(null);
|
||||
|
||||
// 使用 setTimeout 确保状态更新被 React 检测到
|
||||
setTimeout(() => {
|
||||
setSelectedFolderGlobal(newPath);
|
||||
console.log('✅ 已切换到新文件夹, selectedFolder =', newPath);
|
||||
}, 50);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('文件夹重命名失败:', error);
|
||||
alert('重命名失败: ' + (error.message || '未知错误'));
|
||||
} finally {
|
||||
setRenamingFolder(null);
|
||||
setEditingFolderName('');
|
||||
}
|
||||
};
|
||||
|
||||
// 取消文件夹重命名
|
||||
const handleCancelRenameFolder = () => {
|
||||
setRenamingFolder(null);
|
||||
setEditingFolderName('');
|
||||
};
|
||||
|
||||
const handleAddLibrary = async () => {
|
||||
// 扫描期间禁止添加素材库
|
||||
if (isScanning()) {
|
||||
@@ -872,9 +990,33 @@ function Sidebar() {
|
||||
<Folder className="w-4 h-4 mr-2 text-gray-500 flex-shrink-0" />
|
||||
|
||||
{/* 文件夹名称 */}
|
||||
<span className="text-sm text-gray-700 dark:text-gray-300 truncate flex-1">
|
||||
{folder.name}
|
||||
</span>
|
||||
{renamingFolder?.path === folder.path ? (
|
||||
// 编辑模式 - 保持与显示模式相同的样式,只添加下划线提示
|
||||
<input
|
||||
ref={folderNameInputRef}
|
||||
type="text"
|
||||
value={editingFolderName}
|
||||
onChange={(e) => setEditingFolderName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
handleFinishRenameFolder();
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
handleCancelRenameFolder();
|
||||
}
|
||||
}}
|
||||
onBlur={handleFinishRenameFolder}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="flex-1 text-sm text-gray-700 dark:text-gray-300 truncate bg-transparent border-none outline-none focus:outline-none underline decoration-2 decoration-blue-500 underline-offset-2"
|
||||
style={{ padding: 0, margin: 0 }}
|
||||
/>
|
||||
) : (
|
||||
// 显示模式
|
||||
<span className="text-sm text-gray-700 dark:text-gray-300 truncate flex-1">
|
||||
{folder.name}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{/* 图片数量 */}
|
||||
<span className="text-xs text-gray-400 ml-2 flex-shrink-0">{folder.imageCount}</span>
|
||||
@@ -1171,6 +1313,7 @@ function Sidebar() {
|
||||
position={contextMenu.position}
|
||||
onClose={() => setContextMenu({ isOpen: false, position: null, folder: null })}
|
||||
options={contextMenu.folder ? [
|
||||
menuItems.rename(() => handleStartRenameFolder(contextMenu.folder)),
|
||||
menuItems.move(() => handleMoveFolderClick(contextMenu.folder.path)),
|
||||
menuItems.delete(async () => {
|
||||
setContextMenu({ isOpen: false, position: null, folder: null });
|
||||
|
||||
@@ -36,6 +36,9 @@ export const useImageStore = create((set, get) => ({
|
||||
hasMore: false,
|
||||
},
|
||||
|
||||
// 重命名状态
|
||||
renamingImage: null, // 正在重命名的图片
|
||||
|
||||
// 图片操作
|
||||
setImages: (images) => set({ images }),
|
||||
|
||||
@@ -94,5 +97,18 @@ export const useImageStore = create((set, get) => ({
|
||||
// 加载状态
|
||||
setImageLoadingState: (state) => set((prev) => ({
|
||||
imageLoadingState: { ...prev.imageLoadingState, ...state }
|
||||
})),
|
||||
|
||||
// 重命名操作
|
||||
setRenamingImage: (image) => set({ renamingImage: image }),
|
||||
|
||||
// 更新图片信息(重命名后)
|
||||
updateImage: (oldPath, newData) => set((state) => ({
|
||||
images: state.images.map(img =>
|
||||
img.path === oldPath ? { ...img, ...newData } : img
|
||||
),
|
||||
selectedImage: state.selectedImage?.path === oldPath
|
||||
? { ...state.selectedImage, ...newData }
|
||||
: state.selectedImage
|
||||
}))
|
||||
}));
|
||||
Reference in new issue
Block a user