新增 文件操作 复制粘贴
This commit is contained in:
1 parent
7ef71ac6e1
commit
f6c832f240
7 files changed
+606
-33
No files matched your search
@@ -89,19 +89,19 @@ router.post('/move', asyncHandler(async (req, res) => {
|
||||
/**
|
||||
* 复制文件或文件夹
|
||||
* POST /api/file/copy
|
||||
* Body: { libraryId, items: [{type, path}], targetFolder }
|
||||
* Body: { libraryId, items: [{type, path}], targetFolder, conflictAction?: 'skip'|'replace'|'rename' }
|
||||
*/
|
||||
router.post('/copy', asyncHandler(async (req, res) => {
|
||||
const { libraryId, items, targetFolder } = req.body;
|
||||
const { libraryId, items, targetFolder, conflictAction } = req.body;
|
||||
|
||||
if (!libraryId || !items || !Array.isArray(items) || !targetFolder) {
|
||||
if (!libraryId || !items || !Array.isArray(items) || targetFolder === undefined) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: '缺少必要参数'
|
||||
});
|
||||
}
|
||||
|
||||
const results = await fileService.copyItems(libraryId, items, targetFolder);
|
||||
const results = await fileService.copyItems(libraryId, items, targetFolder, conflictAction);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
|
||||
@@ -701,17 +701,24 @@ class FileService {
|
||||
* @param {string} libraryId - 素材库ID
|
||||
* @param {Array} items - 待复制项
|
||||
* @param {string} targetFolder - 目标文件夹(相对路径)
|
||||
* @param {string} conflictAction - 冲突处理方式: 'skip'|'replace'|'rename'
|
||||
*/
|
||||
async copyItems(libraryId, items, targetFolder) {
|
||||
async copyItems(libraryId, items, targetFolder, conflictAction = 'rename') {
|
||||
const db = this._getDatabase(libraryId);
|
||||
const libraryPath = db.libraryPath;
|
||||
const results = { success: [], failed: [] };
|
||||
const results = { success: [], failed: [], conflicts: [] };
|
||||
|
||||
// 确保目标文件夹存在
|
||||
const targetFullPath = path.join(libraryPath, targetFolder || '');
|
||||
if (!fs.existsSync(targetFullPath)) {
|
||||
fs.mkdirSync(targetFullPath, { recursive: true });
|
||||
}
|
||||
|
||||
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);
|
||||
const dstFullPath = path.join(targetFullPath, fileName);
|
||||
|
||||
// 检查源文件是否存在
|
||||
if (!fs.existsSync(srcFullPath)) {
|
||||
@@ -719,31 +726,80 @@ class FileService {
|
||||
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;
|
||||
const isDirectory = item.type === 'folder';
|
||||
|
||||
// 检查是否与源路径相同(在同一文件夹内复制粘贴)
|
||||
if (srcFullPath === dstFullPath) {
|
||||
// 记录冲突
|
||||
results.conflicts.push({ path: item.path, name: fileName });
|
||||
|
||||
while (fs.existsSync(finalDstPath)) {
|
||||
const numberedName = `${basename} (${counter})${ext}`;
|
||||
finalDstPath = path.join(targetFullPath, numberedName);
|
||||
counter++;
|
||||
if (conflictAction === 'skip') {
|
||||
// 跳过:源和目标相同,直接跳过
|
||||
console.log(`⏭️ 跳过(源和目标相同): ${fileName}`);
|
||||
continue;
|
||||
} else if (conflictAction === 'replace') {
|
||||
// 覆盖:源和目标相同,无法覆盖自己,跳过
|
||||
console.log(`⏭️ 跳过(无法覆盖自己): ${fileName}`);
|
||||
continue;
|
||||
} else if (conflictAction === 'rename') {
|
||||
// 重命名:自动编号创建副本
|
||||
const ext = isDirectory ? '' : path.extname(fileName);
|
||||
const basename = isDirectory ? fileName : path.basename(fileName, ext);
|
||||
let counter = 1;
|
||||
|
||||
while (fs.existsSync(finalDstPath)) {
|
||||
const numberedName = isDirectory
|
||||
? `${basename} (${counter})`
|
||||
: `${basename} (${counter})${ext}`;
|
||||
finalDstPath = path.join(targetFullPath, numberedName);
|
||||
counter++;
|
||||
}
|
||||
console.log(`✏️ 创建副本: ${path.basename(finalDstPath)}`);
|
||||
}
|
||||
} else if (fs.existsSync(dstFullPath)) {
|
||||
// 目标文件存在但与源不同
|
||||
results.conflicts.push({ path: item.path, name: fileName });
|
||||
|
||||
if (conflictAction === 'skip') {
|
||||
// 跳过冲突文件
|
||||
console.log(`⏭️ 跳过冲突文件: ${fileName}`);
|
||||
continue;
|
||||
} else if (conflictAction === 'replace') {
|
||||
// 覆盖:先删除目标文件/文件夹
|
||||
console.log(`🔄 覆盖文件: ${fileName}`);
|
||||
if (fs.statSync(dstFullPath).isDirectory()) {
|
||||
fs.rmSync(dstFullPath, { recursive: true, force: true });
|
||||
} else {
|
||||
fs.unlinkSync(dstFullPath);
|
||||
}
|
||||
} else if (conflictAction === 'rename') {
|
||||
// 重命名:自动编号
|
||||
const ext = isDirectory ? '' : path.extname(fileName);
|
||||
const basename = isDirectory ? fileName : path.basename(fileName, ext);
|
||||
let counter = 1;
|
||||
|
||||
while (fs.existsSync(finalDstPath)) {
|
||||
const numberedName = isDirectory
|
||||
? `${basename} (${counter})`
|
||||
: `${basename} (${counter})${ext}`;
|
||||
finalDstPath = path.join(targetFullPath, numberedName);
|
||||
counter++;
|
||||
}
|
||||
console.log(`✏️ 重命名为: ${path.basename(finalDstPath)}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 复制文件或文件夹
|
||||
if (item.type === 'folder') {
|
||||
// 复制整个文件夹
|
||||
fs.cpSync(srcFullPath, finalDstPath, { recursive: true });
|
||||
// TODO: 递归处理文件夹中的所有图片
|
||||
|
||||
// 递归处理文件夹中的所有图片(生成缩略图、入库)
|
||||
await this._processFolderImages(finalDstPath, libraryPath, db);
|
||||
} else {
|
||||
// 复制单个文件
|
||||
fs.copyFileSync(srcFullPath, finalDstPath);
|
||||
|
||||
// 处理新文件(生成缩略图、入库)
|
||||
@@ -752,6 +808,7 @@ class FileService {
|
||||
|
||||
const newRelativePath = path.relative(libraryPath, finalDstPath).replace(/\\/g, '/');
|
||||
results.success.push({ oldPath: item.path, newPath: newRelativePath });
|
||||
console.log(`✅ 复制成功: ${item.path} → ${newRelativePath}`);
|
||||
} catch (error) {
|
||||
console.error(`复制失败 ${item.path}:`, error.message);
|
||||
results.failed.push({ path: item.path, error: error.message });
|
||||
@@ -766,6 +823,38 @@ class FileService {
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归处理文件夹中的所有图片
|
||||
* @private
|
||||
*/
|
||||
async _processFolderImages(folderPath, libraryPath, db) {
|
||||
const entries = fs.readdirSync(folderPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = path.join(folderPath, entry.name);
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
// 跳过 .flypic 目录
|
||||
if (entry.name === '.flypic') continue;
|
||||
|
||||
// 递归处理子文件夹
|
||||
await this._processFolderImages(fullPath, libraryPath, db);
|
||||
} else {
|
||||
// 检查是否是图片文件
|
||||
const ext = path.extname(entry.name).toLowerCase();
|
||||
const imageExts = ['.jpg', '.jpeg', '.png', '.webp', '.gif', '.bmp', '.tiff'];
|
||||
|
||||
if (imageExts.includes(ext)) {
|
||||
try {
|
||||
await processImage(fullPath, libraryPath, db);
|
||||
} catch (error) {
|
||||
console.warn(`处理图片失败 ${entry.name}:`, error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新文件元数据(评分、收藏、标签)
|
||||
* @param {string} libraryId - 素材库ID
|
||||
|
||||
@@ -54,12 +54,14 @@ export const fileAPI = {
|
||||
* @param {string} libraryId - 素材库ID
|
||||
* @param {Array} items - 待复制项
|
||||
* @param {string} targetFolder - 目标文件夹路径
|
||||
* @param {string} conflictAction - 冲突处理方式: 'skip'|'replace'|'rename'
|
||||
*/
|
||||
async copy(libraryId, items, targetFolder) {
|
||||
async copy(libraryId, items, targetFolder, conflictAction = 'rename') {
|
||||
const response = await axios.post(`${API_BASE}/api/file/copy`, {
|
||||
libraryId,
|
||||
items,
|
||||
targetFolder
|
||||
targetFolder,
|
||||
conflictAction
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* 文件冲突处理对话框
|
||||
*/
|
||||
|
||||
import { X, AlertTriangle } from 'lucide-react';
|
||||
|
||||
function ConflictDialog({ isOpen, conflicts, onResolve, onCancel }) {
|
||||
if (!isOpen) return null;
|
||||
|
||||
const handleResolveAll = (action) => {
|
||||
onResolve(action);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full mx-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertTriangle className="w-5 h-5 text-yellow-500" />
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
|
||||
文件冲突
|
||||
</h3>
|
||||
</div>
|
||||
<button
|
||||
onClick={onCancel}
|
||||
className="p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded"
|
||||
>
|
||||
<X className="w-5 h-5 text-gray-500" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="p-4">
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
|
||||
{conflicts.some(c => c.isSameLocation) ? (
|
||||
<>
|
||||
正在同一位置复制 <span className="font-semibold text-gray-900 dark:text-white">{conflicts.length}</span> 个文件/文件夹
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
目标位置已存在 <span className="font-semibold text-gray-900 dark:text-white">{conflicts.length}</span> 个同名文件/文件夹
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
|
||||
{/* Conflict List */}
|
||||
<div className="mb-4 max-h-40 overflow-y-auto bg-gray-50 dark:bg-gray-900 rounded p-3">
|
||||
{conflicts.slice(0, 5).map((conflict, index) => (
|
||||
<div key={index} className="text-sm text-gray-700 dark:text-gray-300 mb-1">
|
||||
• {conflict.name}
|
||||
{conflict.isSameLocation && (
|
||||
<span className="ml-2 text-xs text-blue-500 dark:text-blue-400">(同位置)</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{conflicts.length > 5 && (
|
||||
<div className="text-sm text-gray-500 dark:text-gray-400">
|
||||
... 还有 {conflicts.length - 5} 个文件
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
|
||||
请选择如何处理:
|
||||
</p>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="space-y-2">
|
||||
<button
|
||||
onClick={() => handleResolveAll('skip')}
|
||||
className="w-full px-4 py-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-900 dark:text-white rounded-lg transition-colors text-left"
|
||||
>
|
||||
<div className="font-medium">跳过</div>
|
||||
<div className="text-xs text-gray-600 dark:text-gray-400">
|
||||
{conflicts.some(c => c.isSameLocation)
|
||||
? '不创建副本,保持原样'
|
||||
: '保留现有文件,不复制冲突的文件'}
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => handleResolveAll('replace')}
|
||||
className="w-full px-4 py-2 bg-yellow-100 hover:bg-yellow-200 dark:bg-yellow-900 dark:hover:bg-yellow-800 text-gray-900 dark:text-white rounded-lg transition-colors text-left"
|
||||
>
|
||||
<div className="font-medium">覆盖</div>
|
||||
<div className="text-xs text-gray-600 dark:text-gray-400">
|
||||
{conflicts.some(c => c.isSameLocation)
|
||||
? '无法覆盖自己,将跳过'
|
||||
: '用新文件替换现有文件'}
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => handleResolveAll('rename')}
|
||||
className="w-full px-4 py-2 bg-blue-100 hover:bg-blue-200 dark:bg-blue-900 dark:hover:bg-blue-800 text-gray-900 dark:text-white rounded-lg transition-colors text-left"
|
||||
>
|
||||
<div className="font-medium">保留两者(推荐)</div>
|
||||
<div className="text-xs text-gray-600 dark:text-gray-400">
|
||||
自动重命名为 "文件名 (1).ext"
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="flex justify-end gap-2 p-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<button
|
||||
onClick={onCancel}
|
||||
className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ConflictDialog;
|
||||
@@ -7,12 +7,14 @@ import { useLibraryStore } from '../stores/useLibraryStore';
|
||||
import { useImageStore } from '../stores/useImageStore';
|
||||
import { useUIStore } from '../stores/useUIStore';
|
||||
import { useScanStore } from '../stores/useScanStore';
|
||||
import { useClipboardStore } from '../stores/useClipboardStore';
|
||||
import { imageAPI, fileAPI } from '../api';
|
||||
import requestManager, { RequestType } from '../services/requestManager';
|
||||
import FileViewer from './FileViewer';
|
||||
import ContextMenu, { menuItems } from './ContextMenu';
|
||||
import UndoToast from './UndoToast';
|
||||
import FolderSelector from './FolderSelector';
|
||||
import ConflictDialog from './ConflictDialog';
|
||||
|
||||
// 虚拟滚动阈值:超过此数量启用虚拟滚动
|
||||
const VIRTUAL_SCROLL_THRESHOLD = 100;
|
||||
@@ -123,6 +125,10 @@ function ImageWaterfall() {
|
||||
const [moveItems, setMoveItems] = useState([]); // 待移动的项
|
||||
const [editingFilename, setEditingFilename] = useState(''); // 编辑中的文件名
|
||||
const editInputRef = useRef(null); // 编辑输入框引用
|
||||
const [conflictDialog, setConflictDialog] = useState({ isOpen: false, conflicts: [], pendingPaste: null }); // 冲突对话框
|
||||
|
||||
// 剪贴板状态
|
||||
const { copyToClipboard, getClipboard, hasClipboard } = useClipboardStore();
|
||||
|
||||
// 监听文件夹切换,切换时关闭Toast
|
||||
useEffect(() => {
|
||||
@@ -130,12 +136,30 @@ function ImageWaterfall() {
|
||||
setUndoToast({ isVisible: false, message: '', count: 0 });
|
||||
}, [selectedFolder]);
|
||||
|
||||
// 全局快捷键监听 - Del 键删除, Ctrl+Z 撤销, F2/Enter 重命名
|
||||
// 全局快捷键监听 - Del 键删除, Ctrl+Z 撤销, F2/Enter 重命名, Ctrl+C 复制, Ctrl+V 粘贴
|
||||
useEffect(() => {
|
||||
const handleGlobalKeyDown = async (e) => {
|
||||
// 忽略输入框中的快捷键
|
||||
if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
|
||||
|
||||
// Ctrl+C → 复制
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 'c') {
|
||||
if (selectedImages.length > 0 || selectedImage) {
|
||||
e.preventDefault();
|
||||
handleCopy();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Ctrl+V → 粘贴
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 'v') {
|
||||
if (hasClipboard() && selectedFolder) {
|
||||
e.preventDefault();
|
||||
await handlePaste();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Ctrl+Z → 撤销
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 'z') {
|
||||
e.preventDefault();
|
||||
@@ -163,7 +187,7 @@ function ImageWaterfall() {
|
||||
|
||||
window.addEventListener('keydown', handleGlobalKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleGlobalKeyDown);
|
||||
}, [selectedImages, selectedImage, images, currentLibraryId, undoHistory]);
|
||||
}, [selectedImages, selectedImage, images, currentLibraryId, undoHistory, selectedFolder, hasClipboard]);
|
||||
|
||||
// 简单的向下无限滚动加载
|
||||
const loadMoreImages = useCallback(async () => {
|
||||
@@ -697,6 +721,274 @@ function ImageWaterfall() {
|
||||
}
|
||||
}, [currentLibraryId, moveItems, images, setImages, clearSelection, setFolders]);
|
||||
|
||||
// 复制图片到系统剪贴板(支持多图,使用 HTML 格式)
|
||||
const copyImagesToSystemClipboard = async (images) => {
|
||||
try {
|
||||
// 检查 Clipboard API 是否可用
|
||||
if (typeof ClipboardItem === 'undefined' || !navigator.clipboard || typeof navigator.clipboard.write !== 'function') {
|
||||
console.warn('系统剪贴板 API 不可用');
|
||||
return false;
|
||||
}
|
||||
|
||||
if (images.length === 0) return false;
|
||||
|
||||
// 单张图片:直接复制为 PNG
|
||||
if (images.length === 1) {
|
||||
try {
|
||||
const img = images[0];
|
||||
const imageUrl = `/api/image/original/${currentLibraryId}/${img.path}`;
|
||||
const response = await fetch(imageUrl);
|
||||
const blob = await response.blob();
|
||||
|
||||
// 转换为 PNG
|
||||
const canvas = document.createElement('canvas');
|
||||
const image = new Image();
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
image.onload = resolve;
|
||||
image.onerror = reject;
|
||||
image.src = URL.createObjectURL(blob);
|
||||
});
|
||||
|
||||
canvas.width = image.width;
|
||||
canvas.height = image.height;
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.drawImage(image, 0, 0);
|
||||
|
||||
URL.revokeObjectURL(image.src);
|
||||
|
||||
const pngBlob = await new Promise((resolve) => {
|
||||
canvas.toBlob(resolve, 'image/png');
|
||||
});
|
||||
|
||||
await navigator.clipboard.write([
|
||||
new ClipboardItem({
|
||||
'image/png': pngBlob
|
||||
})
|
||||
]);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn('单图复制失败:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 多张图片:使用 HTML 格式(包含所有图片的 base64)
|
||||
try {
|
||||
const imageDataList = await Promise.all(
|
||||
images.map(async (img) => {
|
||||
const imageUrl = `/api/image/original/${currentLibraryId}/${img.path}`;
|
||||
const response = await fetch(imageUrl);
|
||||
const blob = await response.blob();
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
resolve({
|
||||
dataUrl: reader.result,
|
||||
filename: img.filename
|
||||
});
|
||||
};
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
// 创建 HTML 格式(使用 span 包裹每张图片,消除间距)
|
||||
const htmlContent = imageDataList.map(({ dataUrl, filename }) => `<span><img src="${dataUrl}" alt="${filename}"></span>`).join('');
|
||||
|
||||
// 创建纯文本格式(文件名列表)
|
||||
const textContent = images.map(img => img.filename).join('\n');
|
||||
|
||||
await navigator.clipboard.write([
|
||||
new ClipboardItem({
|
||||
'text/html': new Blob([htmlContent], { type: 'text/html' }),
|
||||
'text/plain': new Blob([textContent], { type: 'text/plain' })
|
||||
})
|
||||
]);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn('多图复制失败:', error);
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('写入系统剪贴板失败:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// 复制到剪贴板(立即更新应用内剪贴板,异步写入系统剪贴板)
|
||||
const handleCopy = useCallback(() => {
|
||||
const imagesToCopy = selectedImages.length > 0
|
||||
? selectedImages
|
||||
: selectedImage
|
||||
? [selectedImage]
|
||||
: [];
|
||||
|
||||
if (imagesToCopy.length === 0) return;
|
||||
|
||||
// 1. 立即写入应用内剪贴板(用于应用内粘贴,同步操作)
|
||||
const itemsToCopy = imagesToCopy.map(img => ({ type: 'file', path: img.path, data: img }));
|
||||
copyToClipboard(itemsToCopy, 'copy');
|
||||
console.log(`📋 已复制 ${itemsToCopy.length} 个文件到应用内剪贴板`);
|
||||
|
||||
// 2. 立即显示Toast
|
||||
setUndoToast({
|
||||
isVisible: true,
|
||||
message: `已复制 ${itemsToCopy.length} 个文件`,
|
||||
count: itemsToCopy.length
|
||||
});
|
||||
|
||||
// 3秒后自动隐藏
|
||||
setTimeout(() => {
|
||||
setUndoToast({ isVisible: false, message: '', count: 0 });
|
||||
}, 3000);
|
||||
|
||||
// 3. 异步写入系统剪贴板(用于跨应用粘贴,不阻塞)
|
||||
copyImagesToSystemClipboard(imagesToCopy).then(success => {
|
||||
if (success) {
|
||||
console.log(`✅ 已写入系统剪贴板,可粘贴到外部应用`);
|
||||
}
|
||||
});
|
||||
}, [selectedImages, selectedImage, copyToClipboard, currentLibraryId]);
|
||||
|
||||
// 粘贴(先检查冲突)
|
||||
const handlePaste = useCallback(async () => {
|
||||
if (!currentLibraryId || !selectedFolder) return;
|
||||
|
||||
const { items } = getClipboard();
|
||||
if (!items || items.length === 0) return;
|
||||
|
||||
// 检查目标文件夹中是否存在同名文件(包括源文件本身)
|
||||
const targetFolderImages = images.filter(img => img.folder === selectedFolder);
|
||||
const conflicts = [];
|
||||
|
||||
for (const item of items) {
|
||||
const fileName = item.path.split('/').pop();
|
||||
const itemFolder = item.path.substring(0, item.path.lastIndexOf('/'));
|
||||
|
||||
// 检查是否存在同名文件(包括源文件本身)
|
||||
const exists = targetFolderImages.some(img => img.filename === fileName);
|
||||
|
||||
if (exists) {
|
||||
conflicts.push({
|
||||
path: item.path,
|
||||
name: fileName,
|
||||
isSameLocation: itemFolder === selectedFolder // 标记是否在同一位置
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 如果有冲突,显示对话框
|
||||
if (conflicts.length > 0) {
|
||||
setConflictDialog({
|
||||
isOpen: true,
|
||||
conflicts,
|
||||
pendingPaste: { items, targetFolder: selectedFolder }
|
||||
});
|
||||
} else {
|
||||
// 没有冲突,直接执行粘贴
|
||||
await executePaste(items, selectedFolder, 'rename');
|
||||
}
|
||||
}, [currentLibraryId, selectedFolder, getClipboard, images]);
|
||||
|
||||
// 执行粘贴操作
|
||||
const executePaste = useCallback(async (items, targetFolder, conflictAction) => {
|
||||
if (!currentLibraryId) return;
|
||||
|
||||
console.log(`📋 开始粘贴 ${items.length} 个文件到: ${targetFolder}`);
|
||||
|
||||
// 1. 立即更新文件夹计数(乐观更新)
|
||||
const { folders, setFolders } = useImageStore.getState();
|
||||
const originalFolders = folders; // 保存用于回滚
|
||||
|
||||
if (folders && folders.length > 0) {
|
||||
const updatedFolders = folders.map(folder => {
|
||||
// 更新目标文件夹及其所有父文件夹的计数
|
||||
if (folder.path === targetFolder || targetFolder.startsWith(folder.path + '/')) {
|
||||
return {
|
||||
...folder,
|
||||
count: (folder.count || 0) + items.length
|
||||
};
|
||||
}
|
||||
return folder;
|
||||
});
|
||||
setFolders(updatedFolders);
|
||||
}
|
||||
|
||||
// 2. 立即显示Toast
|
||||
setUndoToast({
|
||||
isVisible: true,
|
||||
message: `已粘贴 ${items.length} 个文件`,
|
||||
count: items.length
|
||||
});
|
||||
|
||||
// 3秒后自动隐藏
|
||||
setTimeout(() => {
|
||||
setUndoToast({ isVisible: false, message: '', count: 0 });
|
||||
}, 3000);
|
||||
|
||||
// 3. 后台执行API调用(串行,确保文件夹数据是最新的)
|
||||
(async () => {
|
||||
try {
|
||||
// 先执行复制
|
||||
const result = await fileAPI.copy(currentLibraryId, items, targetFolder, conflictAction);
|
||||
|
||||
// 处理结果
|
||||
const successCount = result.data.success?.length || 0;
|
||||
const failedCount = result.data.failed?.length || 0;
|
||||
|
||||
if (failedCount > 0) {
|
||||
// 有失败的项,更新Toast提示
|
||||
setUndoToast({
|
||||
isVisible: true,
|
||||
message: successCount > 0
|
||||
? `已粘贴 ${successCount} 个文件,${failedCount} 个失败`
|
||||
: `粘贴失败: ${result.data.failed[0].error}`,
|
||||
count: successCount
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
setUndoToast({ isVisible: false, message: '', count: 0 });
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// 刷新当前文件夹的图片列表
|
||||
if (selectedFolder === targetFolder) {
|
||||
const params = { folder: selectedFolder };
|
||||
const response = await imageAPI.search(currentLibraryId, params);
|
||||
setImages(response.images);
|
||||
}
|
||||
|
||||
// 复制完成后再刷新文件夹列表(确保拿到最新数据)
|
||||
const foldersRes = await imageAPI.getFolders(currentLibraryId);
|
||||
setFolders(foldersRes.folders);
|
||||
} catch (error) {
|
||||
console.error('粘贴失败:', error);
|
||||
// 失败时回滚文件夹计数
|
||||
setFolders(originalFolders);
|
||||
setUndoToast({ isVisible: false, message: '', count: 0 });
|
||||
alert('粘贴失败: ' + (error.message || '未知错误'));
|
||||
}
|
||||
})();
|
||||
}, [currentLibraryId, selectedFolder, setImages]);
|
||||
|
||||
// 处理冲突对话框的选择
|
||||
const handleConflictResolve = useCallback(async (action) => {
|
||||
const { pendingPaste } = conflictDialog;
|
||||
if (!pendingPaste) return;
|
||||
|
||||
setConflictDialog({ isOpen: false, conflicts: [], pendingPaste: null });
|
||||
await executePaste(pendingPaste.items, pendingPaste.targetFolder, action);
|
||||
}, [conflictDialog, executePaste]);
|
||||
|
||||
// 取消冲突对话框
|
||||
const handleConflictCancel = useCallback(() => {
|
||||
setConflictDialog({ isOpen: false, conflicts: [], pendingPaste: null });
|
||||
}, []);
|
||||
|
||||
// 开始重命名
|
||||
const handleStartRename = useCallback((image) => {
|
||||
if (!image) return;
|
||||
@@ -776,6 +1068,10 @@ function ImageWaterfall() {
|
||||
}
|
||||
|
||||
menuOptions.push(
|
||||
menuItems.copy(() => {
|
||||
setContextMenu({ isOpen: false, position: null, image: null });
|
||||
handleCopy();
|
||||
}),
|
||||
menuItems.move(handleMoveClick),
|
||||
menuItems.delete(async () => {
|
||||
setContextMenu({ isOpen: false, position: null, image: null });
|
||||
@@ -784,7 +1080,7 @@ function ImageWaterfall() {
|
||||
);
|
||||
|
||||
return menuOptions;
|
||||
}, [selectedImages, selectedImage, handleMoveClick, handleStartRename]);
|
||||
}, [selectedImages, selectedImage, handleMoveClick, handleStartRename, handleCopy]);
|
||||
|
||||
// 渲染单个图片单元格
|
||||
const renderImageCell = (image, flatIndex) => {
|
||||
@@ -1069,6 +1365,14 @@ function ImageWaterfall() {
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 冲突处理对话框 */}
|
||||
<ConflictDialog
|
||||
isOpen={conflictDialog.isOpen}
|
||||
conflicts={conflictDialog.conflicts}
|
||||
onResolve={handleConflictResolve}
|
||||
onCancel={handleConflictCancel}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useLibraryStore } from '../stores/useLibraryStore';
|
||||
import { useImageStore } from '../stores/useImageStore';
|
||||
import { useUIStore } from '../stores/useUIStore';
|
||||
import { useScanStore } from '../stores/useScanStore';
|
||||
import { useClipboardStore } from '../stores/useClipboardStore';
|
||||
import { imageAPI, fileAPI } from '../api';
|
||||
import JSZip from 'jszip';
|
||||
|
||||
@@ -11,6 +12,7 @@ function RightPanel() {
|
||||
const { currentLibraryId } = useLibraryStore();
|
||||
const { selectedImage, selectedImages, selectedFolder, images, setSelectedImage, updateImage } = useImageStore();
|
||||
const { setMobileView, isResizingPanels, resizingSide } = useUIStore();
|
||||
const { copyToClipboard } = useClipboardStore();
|
||||
const [isMobile, setIsMobile] = useState(false);
|
||||
const [imageUrl, setImageUrl] = useState(''); // 当前显示的图片URL
|
||||
const [isLoadingOriginal, setIsLoadingOriginal] = useState(false);
|
||||
@@ -410,7 +412,12 @@ function RightPanel() {
|
||||
// 复制图片到剪贴板(支持粘贴到聊天软件和文件管理器)
|
||||
const copyImageToClipboard = async () => {
|
||||
try {
|
||||
// 获取原图URL
|
||||
// 1. 先写入应用内剪贴板(同步,用于应用内粘贴)
|
||||
const itemsToCopy = [{ type: 'file', path: selectedImage.path, data: selectedImage }];
|
||||
copyToClipboard(itemsToCopy, 'copy');
|
||||
console.log(`📋 已复制 1 个文件到应用内剪贴板`);
|
||||
|
||||
// 2. 获取原图URL,写入系统剪贴板
|
||||
const imageUrl = imageAPI.getOriginalUrl(currentLibraryId, selectedImage.path);
|
||||
|
||||
// 方案1:尝试现代 Clipboard API(需要 HTTPS)
|
||||
@@ -590,6 +597,11 @@ function RightPanel() {
|
||||
try {
|
||||
const imagesToCopy = getImagesToProcess();
|
||||
|
||||
// 1. 先写入应用内剪贴板(同步,用于应用内粘贴)
|
||||
const itemsToCopy = imagesToCopy.map(img => ({ type: 'file', path: img.path, data: img }));
|
||||
copyToClipboard(itemsToCopy, 'copy');
|
||||
console.log(`📋 已复制 ${itemsToCopy.length} 个文件到应用内剪贴板`);
|
||||
|
||||
if (imagesToCopy.length === 1) {
|
||||
// 单张图片:直接复制
|
||||
await copyImageToClipboard();
|
||||
@@ -628,10 +640,8 @@ function RightPanel() {
|
||||
})
|
||||
);
|
||||
|
||||
// 创建 HTML 格式
|
||||
const htmlContent = imageDataList.map(({ dataUrl, filename }) =>
|
||||
`<img src="${dataUrl}" alt="${filename}" style="display:block; margin:10px 0;">`
|
||||
).join('\n');
|
||||
// 创建 HTML 格式(使用 span 包裹每张图片,消除间距)
|
||||
const htmlContent = imageDataList.map(({ dataUrl, filename }) => `<span><img src="${dataUrl}" alt="${filename}"></span>`).join('');
|
||||
|
||||
await navigator.clipboard.write([
|
||||
new ClipboardItem({
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* 剪贴板状态管理
|
||||
* 管理复制的文件和文件夹
|
||||
*/
|
||||
|
||||
import { create } from 'zustand';
|
||||
|
||||
export const useClipboardStore = create((set, get) => ({
|
||||
// 剪贴板数据
|
||||
clipboardItems: [], // [{type: 'file'|'folder', path: string, data: object}]
|
||||
clipboardType: null, // 'copy' | 'cut' | null
|
||||
|
||||
/**
|
||||
* 复制项目到剪贴板
|
||||
*/
|
||||
copyToClipboard: (items, type = 'copy') => {
|
||||
set({
|
||||
clipboardItems: items,
|
||||
clipboardType: type
|
||||
});
|
||||
console.log(`📋 已复制 ${items.length} 个项目到剪贴板`);
|
||||
},
|
||||
|
||||
/**
|
||||
* 清空剪贴板
|
||||
*/
|
||||
clearClipboard: () => {
|
||||
set({
|
||||
clipboardItems: [],
|
||||
clipboardType: null
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 获取剪贴板内容
|
||||
*/
|
||||
getClipboard: () => {
|
||||
const { clipboardItems, clipboardType } = get();
|
||||
return { items: clipboardItems, type: clipboardType };
|
||||
},
|
||||
|
||||
/**
|
||||
* 检查剪贴板是否有内容
|
||||
*/
|
||||
hasClipboard: () => {
|
||||
return get().clipboardItems.length > 0;
|
||||
}
|
||||
}));
|
||||
Reference in new issue
Block a user