This commit is contained in:
Chen committed 2025-12-01 10:15:32 +08:00
commit 9e346c7d5b
73 files changed
+19169

No files matched your search

+473
View File
@@ -0,0 +1,473 @@
import { useEffect, useState, useRef } from 'react';
import { io } from 'socket.io-client';
import useStore from './store/useStore';
import { libraryAPI, imageAPI, scanAPI } from './services/api';
import Sidebar from './components/Sidebar';
import MainContent from './components/MainContent';
import RightPanel from './components/RightPanel';
import Header from './components/Header';
function App() {
const {
theme,
setLibraries,
setCurrentLibrary,
setScanProgress,
mobileView,
setMobileView,
selectedImage
} = useStore();
const [leftWidth, setLeftWidth] = useState(256); // 默认 256px (w-64)
const [rightWidth, setRightWidth] = useState(320); // 默认 320px (w-80)
const [isDraggingLeft, setIsDraggingLeft] = useState(false);
const [isDraggingRight, setIsDraggingRight] = useState(false);
const [isMobile, setIsMobile] = useState(false);
const containerRef = useRef(null);
useEffect(() => {
// Apply theme
if (theme === 'dark') {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
}, [theme]);
// 检测屏幕尺寸
useEffect(() => {
const checkMobile = () => {
const mobile = window.innerWidth < 768; // < 768px 为移动端
setIsMobile(mobile);
};
checkMobile();
window.addEventListener('resize', checkMobile);
return () => window.removeEventListener('resize', checkMobile);
}, []);
// 选中图片时自动切换到详情视图(移动端)
useEffect(() => {
if (isMobile && selectedImage) {
setMobileView('detail');
}
}, [selectedImage, isMobile, setMobileView]);
useEffect(() => {
// Setup Socket.IO - 开发模式连接后端端口,生产模式使用同源
const socketUrl = import.meta.env.DEV
? 'http://localhost:3000' // 开发模式:后端端口
: window.location.origin; // 生产模式:同源
console.log('🔌 Connecting to Socket.IO:', socketUrl);
const socket = io(socketUrl, {
transports: ['websocket', 'polling'], // 优先使用 websocket
reconnection: true,
reconnectionDelay: 1000,
reconnectionAttempts: 5
});
socket.on('connect', () => {
console.log('✅ Socket.IO connected:', socket.id);
});
socket.on('disconnect', () => {
console.log('❌ Socket.IO disconnected');
});
socket.on('connect_error', (error) => {
console.error('❌ Socket.IO connection error:', error);
});
socket.on('scanProgress', (progress) => {
// 只显示当前素材库的进度
const currentLibId = useStore.getState().currentLibraryId;
if (progress.libraryId === currentLibId) {
setScanProgress(progress);
}
});
socket.on('scanComplete', ({ libraryId, results }) => {
console.log('📊 Scan complete:', { libraryId, results });
// Only reload if this is the current library
const currentLibId = useStore.getState().currentLibraryId;
console.log('🔍 Current library:', currentLibId, 'Scan library:', libraryId, 'Match:', libraryId === currentLibId);
if (libraryId === currentLibId) {
console.log('🔄 Reloading folders and images...');
// 获取当前的筛选条件
const state = useStore.getState();
const params = {
keywords: state.searchKeywords,
...state.filters
};
// 只有选中了文件夹才添加 folder 参数
if (state.selectedFolder) {
params.folder = state.selectedFolder;
}
// 并行加载文件夹和图片
Promise.all([
imageAPI.getFolders(libraryId),
// 如果没有选中文件夹且没有搜索条件,不加载图片(保持在 Dashboard)
(state.selectedFolder || state.searchKeywords || state.filters.formats.length > 0)
? imageAPI.search(libraryId, params)
: Promise.resolve({ data: { images: [] } }),
// 扫描完成后总是重新获取总数
imageAPI.getCount(libraryId)
]).then(([foldersRes, imagesRes, countRes]) => {
useStore.getState().setFolders(foldersRes.data.folders);
useStore.getState().setImages(imagesRes.data.images);
// 更新图片总数
useStore.getState().setTotalImageCount(countRes.data.count);
console.log(`✅ Data reloaded, total: ${countRes.data.count}`);
}).catch(err => {
console.error('❌ Error reloading data:', err);
}).finally(() => {
// 最后清除进度
setScanProgress(null);
console.log('✅ Scan progress cleared');
});
} else {
console.log('⚠️ Library mismatch, skipping reload');
// 不是当前素材库,直接清除进度
setScanProgress(null);
}
});
socket.on('scanError', ({ libraryId, error }) => {
setScanProgress(null);
console.error('Scan error:', error);
});
socket.on('scanPaused', ({ libraryId, results }) => {
console.log('⏸️ Scan paused:', { libraryId, results });
// 保持进度显示,但标记为可以继续
});
// Socket 监听已就绪后,再加载库并可能触发同步
loadLibraries();
return () => {
socket.disconnect();
};
}, []);
const loadLibraries = async () => {
try {
const response = await libraryAPI.getAll();
const { libraries, currentLibraryId: libId, theme: configTheme, preferences } = response.data;
// 立即更新基础状态
setLibraries(libraries);
setCurrentLibrary(libId);
// 加载主题和偏好设置
if (configTheme) {
useStore.getState().setTheme(configTheme);
}
if (preferences) {
const { thumbnailHeight, leftPanelWidth, rightPanelWidth } = preferences;
if (thumbnailHeight) useStore.getState().setThumbnailHeight(thumbnailHeight);
if (leftPanelWidth) setLeftWidth(leftPanelWidth);
if (rightPanelWidth) setRightWidth(rightPanelWidth);
}
if (libId) {
// 并行加载图片和文件夹(加快初始加载速度)
// 优化:启动时不加载全部图片,只加载文件夹
const [foldersRes] = await Promise.all([
imageAPI.getFolders(libId)
]);
useStore.getState().setFolders(foldersRes.data.folders);
// 获取总数
try {
const countRes = await imageAPI.getCount(libId);
useStore.getState().setTotalImageCount(countRes.data.count);
} catch (e) {
console.error('Failed to get image count:', e);
}
console.log('📂 数据加载完成,文件监控器将自动检测变化');
// 后台检查扫描状态(不阻塞主流程)
scanAPI.getStatus(libId).then(scanStatus => {
const { status, progress, pendingCount } = scanStatus.data;
if (status === 'scanning' || status === 'paused') {
console.log(`🔄 恢复扫描状态: ${status}, 进度: ${progress?.percent || 0}%`);
setScanProgress({
...progress,
canStop: true,
isPaused: status === 'paused',
pendingCount: pendingCount
});
}
}).catch(() => { }); // 忽略状态检查错误
}
} catch (error) {
console.error('Error loading libraries:', error);
}
};
const loadImages = async (libraryId) => {
try {
const params = {};
// Get current selected folder
const selectedFolder = useStore.getState().selectedFolder;
if (selectedFolder) {
params.folder = selectedFolder;
}
const response = await imageAPI.search(libraryId, params);
useStore.getState().setImages(response.data.images);
} catch (error) {
console.error('Error loading images:', error);
}
};
const loadFolders = async (libraryId) => {
try {
const response = await imageAPI.getFolders(libraryId);
useStore.getState().setFolders(response.data.folders);
} catch (error) {
console.error('Error loading folders:', error);
}
};
// 保存面板宽度
const savePanelWidths = async (left, right) => {
try {
await libraryAPI.updatePreferences({
leftPanelWidth: left,
rightPanelWidth: right
});
} catch (error) {
console.error('Error saving panel widths:', error);
}
};
// 处理鼠标拖动(极致性能优化 + RAF 批处理)
useEffect(() => {
if (!isDraggingLeft && !isDraggingRight) return;
const leftPanel = document.getElementById('left-panel');
const rightPanel = document.getElementById('right-panel');
let currentLeftWidth = leftWidth;
let currentRightWidth = rightWidth;
// 缓存容器位置,避免重复计算
const containerRect = containerRef.current.getBoundingClientRect();
const containerLeft = containerRect.left;
const containerRight = containerRect.right;
// RAF 批处理,避免一帧多次样式写入
let rafId = null;
let pendingLeft = null;
let pendingRight = null;
const flushStyle = () => {
if (leftPanel && pendingLeft != null) {
leftPanel.style.width = `${pendingLeft}px`;
currentLeftWidth = pendingLeft;
}
if (rightPanel && pendingRight != null) {
rightPanel.style.width = `${pendingRight}px`;
currentRightWidth = pendingRight;
}
rafId = null;
pendingLeft = null;
pendingRight = null;
};
const handleMouseMove = (e) => {
let needSchedule = false;
if (isDraggingLeft && leftPanel) {
const newWidth = e.clientX - containerLeft;
if (newWidth >= 200 && newWidth <= 400) {
pendingLeft = newWidth;
needSchedule = true;
}
}
if (isDraggingRight && rightPanel) {
const newWidth = containerRight - e.clientX;
if (newWidth >= 280 && newWidth <= 500) {
pendingRight = newWidth;
needSchedule = true;
}
}
if (needSchedule && rafId == null) {
rafId = requestAnimationFrame(flushStyle);
}
};
const handleMouseUp = () => {
if (rafId) {
cancelAnimationFrame(rafId);
flushStyle();
}
// 更新 state 并保存
setLeftWidth(currentLeftWidth);
setRightWidth(currentRightWidth);
savePanelWidths(currentLeftWidth, currentRightWidth);
setIsDraggingLeft(false);
setIsDraggingRight(false);
// 拖动结束,恢复
useStore.getState().setIsResizingPanels(false);
useStore.getState().setResizingSide(null);
};
// 使用 passive: false 确保可以阻止默认行为
document.addEventListener('mousemove', handleMouseMove, { passive: true });
document.addEventListener('mouseup', handleMouseUp);
document.body.style.userSelect = 'none';
document.body.style.cursor = 'col-resize';
// 禁用过渡动画
if (leftPanel) leftPanel.style.transition = 'none';
if (rightPanel) rightPanel.style.transition = 'none';
return () => {
if (rafId) {
cancelAnimationFrame(rafId);
rafId = null;
}
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
document.body.style.userSelect = '';
document.body.style.cursor = '';
// 恢复过渡动画
if (leftPanel) leftPanel.style.transition = '';
if (rightPanel) rightPanel.style.transition = '';
};
}, [isDraggingLeft, isDraggingRight]);
// 移动端布局
if (isMobile) {
return (
<div className="flex flex-col h-screen bg-gray-50 dark:bg-gray-900">
<Header />
<div className="flex-1 overflow-hidden relative">
{/* 侧边栏视图 */}
<div className={`absolute inset-0 transition-transform duration-300 ${mobileView === 'sidebar' ? 'translate-x-0' : '-translate-x-full'
}`}>
<Sidebar />
</div>
{/* 主内容视图 */}
<div className={`absolute inset-0 transition-transform duration-300 ${mobileView === 'main' ? 'translate-x-0' :
mobileView === 'sidebar' ? 'translate-x-full' : '-translate-x-full'
}`}>
<MainContent />
</div>
{/* 详情视图 */}
<div className={`absolute inset-0 transition-transform duration-300 ${mobileView === 'detail' ? 'translate-x-0' : 'translate-x-full'
}`}>
<RightPanel />
</div>
</div>
{/* 底部导航 */}
<div className="flex border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
<button
onClick={() => setMobileView('sidebar')}
className={`flex-1 flex flex-col items-center py-2 ${mobileView === 'sidebar' ? 'text-blue-500' : 'text-gray-500'
}`}
>
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
</svg>
<span className="text-xs mt-1">文件夹</span>
</button>
<button
onClick={() => setMobileView('main')}
className={`flex-1 flex flex-col items-center py-2 ${mobileView === 'main' ? 'text-blue-500' : 'text-gray-500'
}`}
>
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
<span className="text-xs mt-1">图片</span>
</button>
<button
onClick={() => setMobileView('detail')}
disabled={!selectedImage}
className={`flex-1 flex flex-col items-center py-2 ${mobileView === 'detail' ? 'text-blue-500' : 'text-gray-500'
} disabled:opacity-30`}
>
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span className="text-xs mt-1">详情</span>
</button>
</div>
</div>
);
}
// 桌面端布局
return (
<div className="flex flex-col h-screen bg-gray-50 dark:bg-gray-900">
<Header />
<div ref={containerRef} className="flex flex-1 overflow-hidden">
{/* 左侧边栏 */}
<div id="left-panel" style={{ width: `${leftWidth}px` }} className="flex-shrink-0 h-full">
<Sidebar />
</div>
{/* 左侧拖动条 */}
<div
className={`group relative w-1 h-full cursor-col-resize flex-shrink-0 transition-colors ${isDraggingLeft ? 'bg-blue-500' : 'bg-gray-200 dark:bg-gray-700 hover:bg-blue-400'
}`}
onMouseDown={(e) => {
e.preventDefault();
// 标记正在拖动,供其他组件抑制重算
useStore.getState().setIsResizingPanels(true);
useStore.getState().setResizingSide('left');
setIsDraggingLeft(true);
}}
>
{/* 扩大点击区域 */}
<div className="absolute inset-y-0 -left-2 -right-2 w-5" />
</div>
{/* 中间主内容区 */}
<div className="flex-1 min-w-0 h-full">
<MainContent />
</div>
{/* 右侧拖动条 */}
<div
className={`group relative w-1 h-full cursor-col-resize flex-shrink-0 transition-colors ${isDraggingRight ? 'bg-blue-500' : 'bg-gray-200 dark:bg-gray-700 hover:bg-blue-400'
}`}
onMouseDown={(e) => {
e.preventDefault();
// 标记正在拖动,供其他组件抑制重算
useStore.getState().setIsResizingPanels(true);
useStore.getState().setResizingSide('right');
setIsDraggingRight(true);
}}
>
{/* 扩大点击区域 */}
<div className="absolute inset-y-0 -left-2 -right-2 w-5" />
</div>
{/* 右侧边栏 */}
<div id="right-panel" style={{ width: `${rightWidth}px` }} className="flex-shrink-0 h-full">
<RightPanel />
</div>
</div>
</div>
);
}
export default App;
+127
View File
@@ -0,0 +1,127 @@
import React from 'react';
import useStore from '../store/useStore';
import { Folder, Image as ImageIcon, Search } from 'lucide-react';
function Dashboard() {
const {
totalImageCount,
folders,
currentLibraryId,
getCurrentLibrary
} = useStore();
const currentLibrary = getCurrentLibrary();
// Calculate stats
const folderCount = folders.length;
// Group folders by parent to find top-level folders
const topLevelFolders = folders.filter(f => !f.parent_path || f.parent_path === '.' || f.parent_path === '');
return (
<div className="flex-1 h-full overflow-y-auto bg-gray-50 dark:bg-gray-900 p-8">
<div className="max-w-4xl mx-auto">
<div className="mb-8">
<h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
{currentLibrary?.name || '素材库'}
</h1>
<p className="text-gray-500 dark:text-gray-400">
{currentLibrary?.path}
</p>
</div>
{/* Stats Cards */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-12">
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm border border-gray-100 dark:border-gray-700">
<div className="flex items-center gap-4">
<div className="p-3 bg-blue-100 dark:bg-blue-900/30 rounded-lg text-blue-600 dark:text-blue-400">
<ImageIcon className="w-6 h-6" />
</div>
<div>
<div className="text-2xl font-bold text-gray-900 dark:text-white">
{totalImageCount.toLocaleString()}
</div>
<div className="text-sm text-gray-500 dark:text-gray-400">总图片数</div>
</div>
</div>
</div>
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm border border-gray-100 dark:border-gray-700">
<div className="flex items-center gap-4">
<div className="p-3 bg-indigo-100 dark:bg-indigo-900/30 rounded-lg text-indigo-600 dark:text-indigo-400">
<Folder className="w-6 h-6" />
</div>
<div>
<div className="text-2xl font-bold text-gray-900 dark:text-white">
{folderCount.toLocaleString()}
</div>
<div className="text-sm text-gray-500 dark:text-gray-400">文件夹</div>
</div>
</div>
</div>
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm border border-gray-100 dark:border-gray-700">
<div className="flex items-center gap-4">
<div className="p-3 bg-purple-100 dark:bg-purple-900/30 rounded-lg text-purple-600 dark:text-purple-400">
<Search className="w-6 h-6" />
</div>
<div>
<div className="text-sm font-medium text-gray-900 dark:text-white mb-1">
快速开始
</div>
<div className="text-xs text-gray-500 dark:text-gray-400">
使用左侧目录树浏览或顶部搜索栏查找图片
</div>
</div>
</div>
</div>
</div>
{/* Top Level Folders Preview */}
{topLevelFolders.length > 0 && (
<div>
<h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-4">
根目录文件夹
</h2>
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
{topLevelFolders.map(folder => (
<div
key={folder.path}
className="bg-white dark:bg-gray-800 rounded-lg p-4 shadow-sm border border-gray-100 dark:border-gray-700 hover:shadow-md transition-shadow cursor-pointer group"
onClick={() => useStore.getState().setSelectedFolder(folder.path)}
>
<div className="flex items-center gap-3 mb-2">
<Folder className="w-8 h-8 text-yellow-500 group-hover:text-yellow-400 transition-colors" />
<div className="flex-1 min-w-0">
<div className="font-medium text-gray-900 dark:text-white truncate" title={folder.name}>
{folder.name}
</div>
</div>
</div>
<div className="text-xs text-gray-500 dark:text-gray-400">
{folder.image_count || 0} 张图片
</div>
</div>
))}
</div>
</div>
)}
{/* Empty State */}
{topLevelFolders.length === 0 && (
<div className="text-center py-12 bg-white dark:bg-gray-800 rounded-xl border border-dashed border-gray-300 dark:border-gray-700">
<Folder className="w-12 h-12 text-gray-300 dark:text-gray-600 mx-auto mb-4" />
<h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
暂无文件夹
</h3>
<p className="text-gray-500 dark:text-gray-400 max-w-sm mx-auto">
您的素材库似乎是空的。请将图片添加到素材库目录中,系统会自动扫描。
</p>
</div>
)}
</div>
</div>
);
}
export default Dashboard;
+124
View File
@@ -0,0 +1,124 @@
import { X, ExternalLink } from 'lucide-react';
import { imageAPI } from '../services/api';
/**
* 文件查看器 - 支持视频播放和文档查看
* 不依赖额外库,使用浏览器原生能力
*/
function FileViewer({ file, libraryId, onClose }) {
if (!file) return null;
const fileType = file.file_type || 'image';
const originalUrl = imageAPI.getOriginalUrl(libraryId, file.path);
// 在系统默认应用中打开
const openInSystem = async () => {
try {
await imageAPI.openInExplorer(libraryId, file.path);
} catch (error) {
console.error('Failed to open file:', error);
}
};
return (
<div className="fixed inset-0 z-50 bg-black bg-opacity-90 flex items-center justify-center">
{/* 顶部工具栏 */}
<div className="absolute top-0 left-0 right-0 h-16 bg-black bg-opacity-50 flex items-center justify-between px-4 z-10">
<div className="text-white text-sm truncate max-w-md">
{file.filename}
</div>
<div className="flex items-center gap-2">
<button
onClick={openInSystem}
className="p-2 text-white hover:bg-white hover:bg-opacity-20 rounded transition-colors"
title="在系统默认应用中打开"
>
<ExternalLink className="w-5 h-5" />
</button>
<button
onClick={onClose}
className="p-2 text-white hover:bg-white hover:bg-opacity-20 rounded transition-colors"
>
<X className="w-6 h-6" />
</button>
</div>
</div>
{/* 内容区域 */}
<div className="w-full h-full flex items-center justify-center p-20">
{fileType === 'video' && (
<video
src={originalUrl}
controls
autoPlay
className="max-w-full max-h-full rounded shadow-2xl"
onError={(e) => {
console.error('Video load error:', e);
alert('视频加载失败,请尝试在系统默认应用中打开');
}}
>
您的浏览器不支持视频播放
</video>
)}
{fileType === 'audio' && (
<div className="flex flex-col items-center justify-center">
<div className="text-white text-6xl mb-8">🎵</div>
<audio
src={originalUrl}
controls
autoPlay
className="w-96 rounded shadow-2xl"
onError={(e) => {
console.error('Audio load error:', e);
alert('音频加载失败,请尝试在系统默认应用中打开');
}}
>
您的浏览器不支持音频播放
</audio>
<p className="text-white mt-4 text-sm opacity-70">{file.filename}</p>
</div>
)}
{fileType === 'document' && (
<div className="w-full h-full bg-white rounded shadow-2xl overflow-hidden">
{file.format === 'pdf' ? (
<iframe
src={originalUrl}
className="w-full h-full"
title={file.filename}
/>
) : (
<iframe
src={originalUrl}
className="w-full h-full"
title={file.filename}
sandbox="allow-same-origin"
/>
)}
</div>
)}
{(fileType === 'design' || fileType === 'other' || !fileType) && (
<div className="text-center text-white">
<p className="mb-4">此文件类型需要在专业软件中打开</p>
<button
onClick={openInSystem}
className="px-6 py-3 bg-blue-500 hover:bg-blue-600 rounded-lg transition-colors"
>
在系统默认应用中打开
</button>
</div>
)}
</div>
{/* 点击背景关闭 */}
<div
className="absolute inset-0 -z-10"
onClick={onClose}
/>
</div>
);
}
export default FileViewer;
+694
View File
@@ -0,0 +1,694 @@
import { useState, useEffect, useMemo, useRef } from 'react';
import { Sun, Moon, Search, Filter, Sliders, RefreshCw } from 'lucide-react';
import useStore from '../store/useStore';
import { libraryAPI, scanAPI, watchAPI } from '../services/api';
function Header() {
const {
theme,
toggleTheme,
searchKeywords,
thumbnailHeight,
images,
filteredImages,
selectedFolder,
currentLibraryId,
setSearchKeywords,
setThumbnailHeight,
setFilteredImages,
mobileView
} = useStore();
const [showFilters, setShowFilters] = useState(false);
const [selectedFormats, setSelectedFormats] = useState([]);
const [selectedSizes, setSelectedSizes] = useState([]);
const [selectedOrientation, setSelectedOrientation] = useState('');
const [isRefreshing, setIsRefreshing] = useState(false);
const [isMobile, setIsMobile] = useState(false);
const [showMobileSettings, setShowMobileSettings] = useState(false);
const [localSearchValue, setLocalSearchValue] = useState(searchKeywords);
const searchDebounceRef = useRef(null);
// 检测移动端
useEffect(() => {
const checkMobile = () => {
setIsMobile(window.innerWidth < 768);
};
checkMobile();
window.addEventListener('resize', checkMobile);
return () => window.removeEventListener('resize', checkMobile);
}, []);
// 监听文件夹变化,自动清空筛选
useEffect(() => {
setSelectedFormats([]);
setSelectedSizes([]);
setSelectedOrientation('');
}, [selectedFolder]);
// 文件监控(默认启用,实时检测文件变化)
useEffect(() => {
if (!currentLibraryId) return;
// 启动文件监控
watchAPI.start(currentLibraryId)
.then(() => {
console.log('✅ 文件监控已启动(实时检测文件变化)');
})
.catch(error => {
console.error('启动文件监控失败:', error);
console.error('提示:在飞牛 fnOS 上,请确保在应用设置中授予了文件夹访问权限');
});
// 清理:关闭监控
return () => {
watchAPI.stop(currentLibraryId).catch(err => console.error('Stop watch error:', err));
};
}, [currentLibraryId]);
// 防抖搜索(300ms 延迟,减少请求频率)
const handleSearchChange = (value) => {
setLocalSearchValue(value);
// 清除之前的定时器
if (searchDebounceRef.current) {
clearTimeout(searchDebounceRef.current);
}
// 300ms 后触发实际搜索
searchDebounceRef.current = setTimeout(() => {
setSearchKeywords(value);
}, 300);
};
// 同步外部 searchKeywords 变化
useEffect(() => {
setLocalSearchValue(searchKeywords);
}, [searchKeywords]);
// 清理定时器
useEffect(() => {
return () => {
if (searchDebounceRef.current) {
clearTimeout(searchDebounceRef.current);
}
};
}, []);
// 智能计算文件大小范围
const calculateSizeRanges = (sizes) => {
if (sizes.length === 0) return [];
const sorted = [...sizes].sort((a, b) => a - b);
const min = sorted[0];
const max = sorted[sorted.length - 1];
if (max - min < 10) {
return [formatSizeRange(min, max)];
}
const rangeCount = 5;
const ranges = [];
const logMin = Math.log10(min || 1);
const logMax = Math.log10(max);
const logStep = (logMax - logMin) / rangeCount;
for (let i = 0; i < rangeCount; i++) {
const rangeStart = Math.pow(10, logMin + i * logStep);
const rangeEnd = Math.pow(10, logMin + (i + 1) * logStep);
const hasImages = sorted.some(size => size >= rangeStart && size < rangeEnd);
if (hasImages || i === rangeCount - 1) {
ranges.push(formatSizeRange(rangeStart, rangeEnd, i === rangeCount - 1));
}
}
return ranges.filter(r => r);
};
// 格式化大小范围
const formatSizeRange = (start, end, isLast = false) => {
const formatSize = (kb) => {
const roundToFriendly = (num) => {
if (num < 10) return Math.round(num);
if (num < 100) return Math.round(num / 5) * 5;
if (num < 1000) return Math.round(num / 10) * 10;
return Math.round(num / 50) * 50;
};
if (kb < 1) return `${roundToFriendly(kb * 1024)}B`;
if (kb < 1024) return `${roundToFriendly(kb)}KB`;
if (kb < 1024 * 1024) return `${roundToFriendly(kb / 1024)}MB`;
return `${roundToFriendly(kb / (1024 * 1024))}GB`;
};
return isLast ? `> ${formatSize(start)}` : `${formatSize(start)} - ${formatSize(end)}`;
};
// 解析大小字符串
const parseSizeToKB = (sizeStr) => {
const match = sizeStr.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB)$/);
if (!match) return 0;
const value = parseFloat(match[1]);
const unit = match[2];
switch (unit) {
case 'B': return value / 1024;
case 'KB': return value;
case 'MB': return value * 1024;
case 'GB': return value * 1024 * 1024;
default: return 0;
}
};
// 匹配大小范围
const matchSizeRange = (sizeKB, range) => {
if (range.startsWith('>')) {
const minStr = range.substring(1).trim();
const minKB = parseSizeToKB(minStr);
return sizeKB >= minKB;
} else if (range.includes(' - ')) {
const [minStr, maxStr] = range.split(' - ').map(s => s.trim());
const minKB = parseSizeToKB(minStr);
const maxKB = parseSizeToKB(maxStr);
return sizeKB >= minKB && sizeKB < maxKB;
}
return false;
};
// 分析当前文件夹的所有图片,生成可选项(只在images变化时计算一次)
const filterOptions = useMemo(() => {
if (images.length === 0) {
return { formats: [], sizes: [], hasHorizontal: false, hasVertical: false };
}
const formats = new Set();
const sizes = [];
let hasHorizontal = false;
let hasVertical = false;
images.forEach(img => {
// 格式
if (img.format) {
formats.add(img.format.toLowerCase());
}
// 文件大小
sizes.push(img.size / 1024);
// 横竖图
if (img.width > img.height) hasHorizontal = true;
if (img.height > img.width) hasVertical = true;
});
// 计算文件大小范围
const sizeRanges = calculateSizeRanges(sizes);
return {
formats: Array.from(formats).sort(),
sizes: sizeRanges,
hasHorizontal,
hasVertical
};
}, [images]);
// 使用 useMemo 缓存筛选结果,避免重复计算
const filteredResult = useMemo(() => {
// 如果没有任何筛选条件,直接返回原始图片
if (selectedFormats.length === 0 &&
selectedSizes.length === 0 &&
!selectedOrientation) {
return images;
}
// 预先转换为 Set 以提高查找性能
const formatSet = new Set(selectedFormats);
const sizeSet = new Set(selectedSizes);
return images.filter(img => {
// 格式筛选
if (formatSet.size > 0) {
if (!formatSet.has(img.format?.toLowerCase())) {
return false;
}
}
// 文件大小筛选
if (sizeSet.size > 0) {
const sizeKB = img.size / 1024;
let matchesSize = false;
for (const range of sizeSet) {
if (matchSizeRange(sizeKB, range)) {
matchesSize = true;
break;
}
}
if (!matchesSize) return false;
}
// 横竖图筛选
if (selectedOrientation === 'horizontal') {
if (img.width <= img.height) return false;
} else if (selectedOrientation === 'vertical') {
if (img.height <= img.width) return false;
}
return true;
});
}, [images, selectedFormats, selectedSizes, selectedOrientation]);
// 更新 filteredImages
useEffect(() => {
setFilteredImages(filteredResult);
}, [filteredResult, setFilteredImages]);
// 切换选项
const toggleFormat = (format) => {
setSelectedFormats(prev =>
prev.includes(format) ? prev.filter(f => f !== format) : [...prev, format]
);
};
const toggleSize = (size) => {
setSelectedSizes(prev =>
prev.includes(size) ? prev.filter(s => s !== size) : [...prev, size]
);
};
const toggleOrientation = (orientation) => {
setSelectedOrientation(prev => prev === orientation ? '' : orientation);
};
// 清除筛选
const clearFilters = () => {
setSelectedFormats([]);
setSelectedSizes([]);
setSelectedOrientation('');
};
const handleThemeToggle = async () => {
toggleTheme();
try {
await libraryAPI.updateTheme(theme === 'light' ? 'dark' : 'light');
} catch (error) {
console.error('Error saving theme:', error);
}
};
const handleThumbnailHeightChange = async (height) => {
setThumbnailHeight(height);
try {
await libraryAPI.updatePreferences({ thumbnailHeight: height });
} catch (error) {
console.error('Error saving preferences:', error);
}
};
const handleRefresh = async () => {
if (!currentLibraryId || isRefreshing) return;
setIsRefreshing(true);
try {
await scanAPI.sync(currentLibraryId);
// Socket.IO 会触发更新
} catch (error) {
console.error('Error refreshing:', error);
alert('刷新失败: ' + error.message);
} finally {
setIsRefreshing(false);
}
};
// 从 filterOptions 中提取可用选项
const availableFormats = filterOptions.formats;
const availableSizes = filterOptions.sizes.map(size => ({ label: size }));
const availableOrientations = [
{ value: 'horizontal', label: '横图' },
{ value: 'vertical', label: '竖图' }
].filter(o =>
(o.value === 'horizontal' && filterOptions.hasHorizontal) ||
(o.value === 'vertical' && filterOptions.hasVertical)
);
// 移动端布局
if (isMobile) {
// 文件夹视图不显示搜索和筛选
const showSearch = mobileView !== 'sidebar';
return (
<header className="border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
{/* 顶部栏 */}
<div className="h-14 flex items-center justify-between px-4">
<h1 className="text-lg font-bold text-gray-900 dark:text-white">FlyPic</h1>
<div className="flex items-center gap-2">
<button
onClick={handleRefresh}
disabled={!currentLibraryId || isRefreshing}
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50"
>
<RefreshCw className={`w-5 h-5 text-gray-700 dark:text-gray-300 ${isRefreshing ? 'animate-spin' : ''}`} />
</button>
<button
onClick={() => setShowMobileSettings(!showMobileSettings)}
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
>
<Sliders className="w-5 h-5 text-gray-700 dark:text-gray-300" />
</button>
<button
onClick={handleThemeToggle}
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
>
{theme === 'light' ? (
<Moon className="w-5 h-5 text-gray-700 dark:text-gray-300" />
) : (
<Sun className="w-5 h-5 text-gray-700 dark:text-gray-300" />
)}
</button>
</div>
</div>
{/* 搜索栏(仅在图片和详情视图显示) */}
{showSearch && (
<div className="px-4 pb-3">
<div className="flex items-center gap-2">
<div className="flex-1 relative">
<Search className="absolute left-3 top-2.5 w-5 h-5 text-gray-400" />
<input
type="text"
placeholder="搜索图片..."
value={searchKeywords}
onChange={(e) => handleSearchChange(e.target.value)}
className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm"
/>
</div>
<button
onClick={() => setShowFilters(!showFilters)}
className={`p-2 border rounded-lg ${
selectedFormats.length > 0 || selectedSizes.length > 0 || selectedOrientation
? 'border-blue-500 bg-blue-50 dark:bg-blue-500/20'
: 'border-gray-300 dark:border-gray-600'
}`}
>
<Filter className={`w-5 h-5 ${
selectedFormats.length > 0 || selectedSizes.length > 0 || selectedOrientation
? 'text-blue-600 dark:text-blue-300'
: 'text-gray-600 dark:text-gray-400'
}`} />
</button>
</div>
</div>
)}
{/* 移动端设置面板 */}
{showMobileSettings && (
<div className="px-4 pb-3 border-t border-gray-200 dark:border-gray-700 pt-3">
<div className="flex flex-col gap-3">
<div className="flex items-center justify-between">
<span className="text-sm text-gray-700 dark:text-gray-300">缩略图大小</span>
<span className="text-sm text-gray-500 dark:text-gray-400">{thumbnailHeight}px</span>
</div>
<input
type="range"
min="150"
max="300"
value={thumbnailHeight}
onChange={(e) => handleThumbnailHeightChange(parseInt(e.target.value))}
className="w-full h-2 bg-gray-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer"
style={{
background: `linear-gradient(to right, #3b82f6 0%, #3b82f6 ${((thumbnailHeight - 150) / 150) * 100}%, #e5e7eb ${((thumbnailHeight - 150) / 150) * 100}%, #e5e7eb 100%)`
}}
/>
</div>
</div>
)}
{/* 筛选面板(仅在图片和详情视图显示) */}
{showSearch && showFilters && (
<div className="px-4 pb-3 border-t border-gray-200 dark:border-gray-700 pt-3">
<div className="flex items-center justify-between mb-3">
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">筛选条件</span>
<button
onClick={clearFilters}
className="text-xs text-blue-500"
>
清除全部
</button>
</div>
{/* 格式筛选 */}
<div className="mb-3">
<div className="text-xs text-gray-500 dark:text-gray-400 mb-2">格式</div>
<div className="flex flex-wrap gap-2">
{availableFormats.map(format => (
<button
key={format}
onClick={() => toggleFormat(format)}
className={`px-3 py-1 text-xs rounded-full ${
selectedFormats.includes(format)
? 'bg-blue-500 text-white'
: 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
}`}
>
{format.toUpperCase()}
</button>
))}
</div>
</div>
{/* 尺寸筛选 */}
<div className="mb-3">
<div className="text-xs text-gray-500 dark:text-gray-400 mb-2">尺寸</div>
<div className="flex flex-wrap gap-2">
{availableSizes.map(size => (
<button
key={size.label}
onClick={() => toggleSize(size.label)}
className={`px-3 py-1 text-xs rounded-full ${
selectedSizes.includes(size.label)
? 'bg-blue-500 text-white'
: 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
}`}
>
{size.label}
</button>
))}
</div>
</div>
{/* 方向筛选 */}
<div>
<div className="text-xs text-gray-500 dark:text-gray-400 mb-2">方向</div>
<div className="flex flex-wrap gap-2">
{availableOrientations.map(orientation => (
<button
key={orientation.value}
onClick={() => toggleOrientation(orientation.value)}
className={`px-3 py-1 text-xs rounded-full ${
selectedOrientation === orientation.value
? 'bg-blue-500 text-white'
: 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
}`}
>
{orientation.label}
</button>
))}
</div>
</div>
</div>
)}
</header>
);
}
// 桌面端布局
return (
<header className="border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
<div className="h-14 flex items-center justify-between px-6">
<div className="flex-shrink-0">
<h1 className="text-xl font-bold text-gray-900 dark:text-white">FlyPic</h1>
<p className="text-xs text-gray-500 dark:text-gray-400">轻量快速的图片素材库管理</p>
</div>
{/* 搜索栏 */}
<div className="flex-1 max-w-2xl mx-6 flex items-center gap-3">
<div className="flex-1 relative">
<Search className="absolute left-3 top-2.5 w-5 h-5 text-gray-400" />
<input
type="text"
placeholder="搜索图片... (多个关键词用空格分隔,即时搜索)"
value={localSearchValue}
onChange={(e) => handleSearchChange(e.target.value)}
className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<button
onClick={() => setShowFilters(!showFilters)}
className={`relative p-2 border rounded-lg transition-colors ${
selectedFormats.length > 0 || selectedSizes.length > 0 || selectedOrientation
? 'border-blue-500 dark:border-blue-400 bg-blue-50 dark:bg-blue-500/20 hover:bg-blue-100 dark:hover:bg-blue-500/30'
: 'border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
title={
selectedFormats.length > 0 || selectedSizes.length > 0 || selectedOrientation
? '筛选(已启用)'
: '筛选'
}
>
<Filter className={`w-5 h-5 ${
selectedFormats.length > 0 || selectedSizes.length > 0 || selectedOrientation
? 'text-blue-600 dark:text-blue-300'
: 'text-gray-600 dark:text-gray-400'
}`} />
{(selectedFormats.length > 0 || selectedSizes.length > 0 || selectedOrientation) && (
<span
className="absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full"
style={{ backgroundColor: '#3b82f6' }}
></span>
)}
</button>
</div>
{/* 缩略图大小滑块 */}
<div className="flex items-center gap-3 flex-shrink-0">
<Sliders className="w-4 h-4 text-gray-500" />
<input
type="range"
min="150"
max="300"
value={thumbnailHeight}
onChange={(e) => handleThumbnailHeightChange(parseInt(e.target.value))}
className="w-32"
/>
<span className="text-sm text-gray-600 dark:text-gray-400 w-12">{thumbnailHeight}px</span>
<button
onClick={handleRefresh}
disabled={!currentLibraryId || isRefreshing}
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed ml-2"
title="手动刷新素材库(文件监控已自动启用)"
>
<RefreshCw className={`w-5 h-5 text-gray-700 dark:text-gray-300 ${isRefreshing ? 'animate-spin' : ''}`} />
</button>
<button
onClick={handleThemeToggle}
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
title={theme === 'light' ? '切换到暗色模式' : '切换到亮色模式'}
>
{theme === 'light' ? (
<Moon className="w-5 h-5 text-gray-700 dark:text-gray-300" />
) : (
<Sun className="w-5 h-5 text-gray-700 dark:text-gray-300" />
)}
</button>
</div>
</div>
{/* 筛选面板 */}
{showFilters && (
<div className="px-6 pb-3">
<div className="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
<div className="flex items-center justify-between mb-3">
<div className="text-sm font-medium text-gray-700 dark:text-gray-300">筛选条件(实时生效)</div>
<button
onClick={clearFilters}
className="text-xs text-blue-500 hover:text-blue-600 dark:hover:text-blue-400"
>
清除全部
</button>
</div>
{/* 三列布局 */}
<div className="grid grid-cols-3 gap-4">
{/* 格式筛选 */}
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">格式</label>
<div className="flex flex-col gap-1.5">
{filterOptions.formats.length > 0 ? (
filterOptions.formats.map(format => (
<button
key={format}
onClick={() => toggleFormat(format)}
className={`px-3 py-1.5 text-xs rounded transition-colors text-left ${
selectedFormats.includes(format)
? 'bg-blue-500 text-white'
: 'bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500'
}`}
>
{format.toUpperCase()}
</button>
))
) : (
<span className="text-xs text-gray-400 py-2">暂无格式数据</span>
)}
</div>
</div>
{/* 文件大小筛选 */}
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">文件大小</label>
<div className="flex flex-col gap-1.5">
{filterOptions.sizes.length > 0 ? (
filterOptions.sizes.map(size => (
<button
key={size}
onClick={() => toggleSize(size)}
className={`px-3 py-1.5 text-xs rounded transition-colors text-left ${
selectedSizes.includes(size)
? 'bg-blue-500 text-white'
: 'bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500'
}`}
>
{size}
</button>
))
) : (
<span className="text-xs text-gray-400 py-2">暂无大小数据</span>
)}
</div>
</div>
{/* 横竖图筛选 */}
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">图片方向</label>
<div className="flex flex-col gap-1.5">
{filterOptions.hasHorizontal && (
<button
onClick={() => toggleOrientation('horizontal')}
className={`px-3 py-1.5 text-xs rounded transition-colors text-left ${
selectedOrientation === 'horizontal'
? 'bg-blue-500 text-white'
: 'bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500'
}`}
>
横图
</button>
)}
{filterOptions.hasVertical && (
<button
onClick={() => toggleOrientation('vertical')}
className={`px-3 py-1.5 text-xs rounded transition-colors text-left ${
selectedOrientation === 'vertical'
? 'bg-blue-500 text-white'
: 'bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500'
}`}
>
竖图
</button>
)}
{!filterOptions.hasHorizontal && !filterOptions.hasVertical && (
<span className="text-xs text-gray-400 py-2">暂无方向数据</span>
)}
</div>
</div>
</div>
</div>
</div>
)}
</header>
);
}
export default Header;
+516
View File
@@ -0,0 +1,516 @@
import { useState, useEffect, useRef, useMemo, useCallback } from 'react';
import { PhotoProvider, PhotoView } from 'react-photo-view';
import 'react-photo-view/dist/react-photo-view.css';
import { VariableSizeList as List } from 'react-window';
import { Play, FileText, Palette, Music, File } from 'lucide-react';
import useStore from '../store/useStore';
import { imageAPI } from '../services/api';
import FileViewer from './FileViewer';
// 虚拟滚动阈值:超过此数量启用虚拟滚动
const VIRTUAL_SCROLL_THRESHOLD = 500;
// Web Worker 阈值:超过此数量使用 Worker 计算布局
const WORKER_THRESHOLD = 200;
function ImageWaterfall() {
const {
filteredImages,
currentLibraryId,
thumbnailHeight,
selectedImage,
setSelectedImage,
selectedImages,
setSelectedImages,
toggleImageSelection,
clearSelection,
isResizingPanels
} = useStore();
const containerRef = useRef(null);
const listRef = useRef(null);
const workerRef = useRef(null);
const requestIdRef = useRef(0);
const [containerWidth, setContainerWidth] = useState(0);
const [containerHeight, setContainerHeight] = useState(0);
const [photoIndex, setPhotoIndex] = useState(-1);
const [lastSelectedIndex, setLastSelectedIndex] = useState(null);
const [viewerFile, setViewerFile] = useState(null);
const [workerRows, setWorkerRows] = useState([]); // Worker 计算的行
// 监听容器宽度变化(使用 ResizeObserver + 去抖/阈值抑制)
useEffect(() => {
let resizeObserver = null;
let retryCount = 0;
const maxRetries = 10;
// 使用 ref 记录上次宽度,避免频繁 setState
const lastWidthRef = { current: 0 };
let debounceTimer = null;
const emitSize = (width, height) => {
// 仅当差异超过阈值时更新,减少重算次数
const threshold = 12; // px
if (Math.abs(width - lastWidthRef.current) < threshold) return true;
lastWidthRef.current = width;
// 去抖:在一小段静止后再更新(拖动时降低重算频率)
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
setContainerWidth(width);
setContainerHeight(height);
}, 50);
return true;
};
const measureAndEmit = () => {
if (containerRef.current) {
// 预留 padding:与现有布局保持一致
const width = containerRef.current.offsetWidth - 32;
const height = containerRef.current.offsetHeight;
if (width > 0) {
return emitSize(width, height);
}
}
return false;
};
const tryInit = () => {
if (measureAndEmit()) {
// 成功获取宽度,设置 ResizeObserver
if (containerRef.current) {
resizeObserver = new ResizeObserver(() => {
// 拖动时跳过更新,避免频繁重算布局
if (useStore.getState().isResizingPanels) return;
measureAndEmit();
});
resizeObserver.observe(containerRef.current);
}
} else if (retryCount < maxRetries) {
// 重试
retryCount++;
requestAnimationFrame(tryInit);
}
};
// 使用 requestAnimationFrame 确保 DOM 已渲染
requestAnimationFrame(tryInit);
return () => {
if (resizeObserver) {
resizeObserver.disconnect();
}
if (debounceTimer) {
clearTimeout(debounceTimer);
}
};
}, []);
// 拖动结束时(isResizingPanels 从 true -> false)立即测量一次
useEffect(() => {
if (isResizingPanels) return;
if (!containerRef.current) return;
const width = containerRef.current.offsetWidth - 32;
const height = containerRef.current.offsetHeight;
if (width > 0) {
setContainerWidth(width);
setContainerHeight(height);
// 重置虚拟列表缓存
if (listRef.current) {
listRef.current.resetAfterIndex(0);
}
}
}, [isResizingPanels]);
// 是否使用 Worker 计算布局
const useWorker = filteredImages.length > WORKER_THRESHOLD;
// 当图片数据变化时重置 Worker 状态(更可靠的重置方式)
const prevImagesLengthRef = useRef(0);
useEffect(() => {
// 图片列表从有到无或数量大幅变化时重置
const prevLen = prevImagesLengthRef.current;
const currLen = filteredImages.length;
if (prevLen > 0 && currLen === 0) {
// 图片被清空,重置 Worker 状态
setWorkerRows([]);
requestIdRef.current = 0;
} else if (currLen > 0 && Math.abs(currLen - prevLen) > prevLen * 0.5) {
// 数量变化超过50%,可能是切换素材库,重置
setWorkerRows([]);
requestIdRef.current = 0;
}
prevImagesLengthRef.current = currLen;
}, [filteredImages.length]);
// 初始化 Web Worker
useEffect(() => {
if (typeof Worker !== 'undefined') {
workerRef.current = new Worker(
new URL('../workers/layoutWorker.js', import.meta.url),
{ type: 'module' }
);
workerRef.current.onmessage = (e) => {
const { rows, requestId, duration, imageCount } = e.data;
// 只处理最新的请求结果
if (requestId === requestIdRef.current) {
setWorkerRows(rows);
if (imageCount > 500) {
console.log(`📐 Worker layout: ${imageCount} images in ${duration.toFixed(1)}ms`);
}
}
};
}
return () => {
if (workerRef.current) {
workerRef.current.terminate();
workerRef.current = null;
}
};
}, []);
// 使用 Worker 计算布局(大量图片时)
useEffect(() => {
if (!useWorker || !workerRef.current || !filteredImages.length || !containerWidth) {
return;
}
const requestId = ++requestIdRef.current;
workerRef.current.postMessage({
images: filteredImages,
containerWidth,
targetHeight: thumbnailHeight,
requestId
});
}, [filteredImages, containerWidth, thumbnailHeight, useWorker]);
// 同步计算布局(少量图片时直接在主线程计算)
const syncRows = useMemo(() => {
// 使用 Worker 时返回空数组,由 workerRows 提供数据
if (useWorker) return [];
if (!filteredImages.length || !containerWidth) {
return [];
}
const gap = 16;
const targetHeight = thumbnailHeight;
const calculatedRows = [];
let currentRow = [];
let currentRowWidthSum = 0;
filteredImages.forEach((image, index) => {
const aspectRatio = image.width / image.height;
const imageWidth = targetHeight * aspectRatio;
currentRow.push({
...image,
originalWidth: imageWidth,
aspectRatio: aspectRatio
});
currentRowWidthSum += imageWidth;
const currentGaps = (currentRow.length - 1) * gap;
const totalWidth = currentRowWidthSum + currentGaps;
const isLastImage = index === filteredImages.length - 1;
let shouldFinishRow = false;
if (isLastImage) {
shouldFinishRow = true;
} else if (totalWidth >= containerWidth * 0.95) {
// Row is almost full (95% or more) - finish it
shouldFinishRow = true;
} else {
// Check if adding next image would overflow too much
const nextImage = filteredImages[index + 1];
if (nextImage) {
const nextAspectRatio = nextImage.width / nextImage.height;
const nextImageWidth = targetHeight * nextAspectRatio;
const nextTotalWidth = currentRowWidthSum + nextImageWidth + (currentRow.length * gap);
// If adding next image would exceed 120% of container width, finish current row
if (nextTotalWidth > containerWidth * 1.2) {
shouldFinishRow = true;
}
}
}
if (shouldFinishRow) {
const totalGaps = (currentRow.length - 1) * gap;
const availableWidth = containerWidth - totalGaps;
// For last row with few images, limit the scale to avoid over-stretching
let scale = availableWidth / currentRowWidthSum;
if (isLastImage && currentRow.length < 3) {
// Last row with 1-2 images: don't stretch too much
scale = Math.min(scale, 1.2);
}
const rowHeight = targetHeight * scale;
currentRow = currentRow.map(img => ({
...img,
calculatedWidth: img.originalWidth * scale,
calculatedHeight: rowHeight
}));
calculatedRows.push(currentRow);
// Reset for next row
currentRow = [];
currentRowWidthSum = 0;
}
});
return calculatedRows;
}, [filteredImages, thumbnailHeight, containerWidth, useWorker]);
// 统一使用的行数据:Worker 模式用 workerRows,否则用 syncRows
const rows = useWorker ? workerRows : syncRows;
const getThumbnailUrl = (image) => {
if (!currentLibraryId || !image.thumbnail_path) return '';
// 提取文件名(兼容反斜杠)
const filename = image.thumbnail_path.replace(/\\/g, '/').split('/').pop();
// 统一使用 480 尺寸(与 Billfish 一致)
return imageAPI.getThumbnailUrl(currentLibraryId, '480', filename);
};
const getOriginalUrl = (image) => {
if (!currentLibraryId) return '';
return imageAPI.getOriginalUrl(currentLibraryId, image.path);
};
// PhotoProvider 使用与布局无关的列表,避免随 containerWidth 变化重建
const providerImages = useMemo(() => {
return filteredImages.map(img => ({ src: getOriginalUrl(img), key: img.id }));
}, [filteredImages, currentLibraryId]);
// 是否启用虚拟滚动
const useVirtualScroll = filteredImages.length > VIRTUAL_SCROLL_THRESHOLD;
// 获取行高(用于虚拟滚动)
const getRowHeight = useCallback((index) => {
if (!rows[index] || rows[index].length === 0) return thumbnailHeight + 40;
// 行高 = 图片高度 + 文件名区域 + 行间距
return rows[index][0].calculatedHeight + 28 + 32;
}, [rows, thumbnailHeight]);
// 当行数据变化时,重置虚拟列表缓存
useEffect(() => {
if (listRef.current && useVirtualScroll) {
listRef.current.resetAfterIndex(0);
}
}, [rows, useVirtualScroll]);
// 扁平化的图片列表(用于 Shift 多选)
const flatImages = useMemo(() => rows.flat(), [rows]);
// 处理图片点击(支持 Ctrl/Shift 多选)
const handleImageClick = useCallback((image, event, imageIndex) => {
if (event.ctrlKey || event.metaKey) {
// Ctrl/Cmd 点击:切换选中状态
event.preventDefault();
toggleImageSelection(image);
setLastSelectedIndex(imageIndex);
} else if (event.shiftKey && lastSelectedIndex !== null) {
// Shift 点击:范围选择
event.preventDefault();
const start = Math.min(lastSelectedIndex, imageIndex);
const end = Math.max(lastSelectedIndex, imageIndex);
const rangeImages = flatImages.slice(start, end + 1);
setSelectedImages(rangeImages);
} else {
// 普通点击:单选
clearSelection();
setSelectedImage(image);
setLastSelectedIndex(imageIndex);
}
}, [flatImages, lastSelectedIndex, toggleImageSelection, setSelectedImages, clearSelection, setSelectedImage]);
// 渲染单个图片单元格
const renderImageCell = (image, flatIndex) => {
const isSingleSelected = selectedImage?.id === image.id;
const isMultiSelected = selectedImages.some(img => img.id === image.id);
const isSelected = isSingleSelected || isMultiSelected;
return (
<div
key={image.id}
className="flex-shrink-0"
style={{ width: `${image.calculatedWidth}px` }}
>
<div
className="relative group cursor-pointer overflow-hidden rounded-lg transition-all hover:shadow-lg"
style={{
height: `${image.calculatedHeight}px`,
backgroundColor: '#2a2a2a',
border: isSelected ? '3px solid #3b82f6' : '3px solid transparent'
}}
onClick={(e) => handleImageClick(image, e, flatIndex)}
onDoubleClick={() => {
const fileType = image.file_type || 'image';
if (fileType === 'image') {
setPhotoIndex(flatIndex);
} else {
setViewerFile(image);
}
}}
>
<img
src={getThumbnailUrl(image)}
alt={image.filename}
className="w-full h-full object-cover"
loading="lazy"
onError={(e) => {
e.target.style.display = 'none';
}}
/>
{/* 文件类型标识 */}
{image.file_type && image.file_type !== 'image' && (
<div className={`absolute top-2 right-2 rounded-md px-2 py-1 flex items-center gap-1 shadow-lg ${
image.file_type === 'video' ? 'bg-blue-500 bg-opacity-90' :
image.file_type === 'audio' ? 'bg-pink-500 bg-opacity-90' :
image.file_type === 'document' ? 'bg-green-500 bg-opacity-90' :
image.file_type === 'design' ? 'bg-purple-500 bg-opacity-90' :
'bg-gray-500 bg-opacity-90'
}`}>
{image.file_type === 'video' && <Play className="w-4 h-4 text-white fill-white" />}
{image.file_type === 'audio' && <Music className="w-4 h-4 text-white" />}
{image.file_type === 'document' && <FileText className="w-4 h-4 text-white" />}
{image.file_type === 'design' && <Palette className="w-4 h-4 text-white" />}
{image.file_type === 'other' && <File className="w-4 h-4 text-white" />}
<span className="text-white text-xs font-semibold uppercase">
{image.format || image.filename.split('.').pop()}
</span>
</div>
)}
<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>
</div>
);
};
// 渲染一行(用于虚拟滚动)
const renderRow = ({ index, style }) => {
const row = rows[index];
if (!row) return null;
// 计算该行之前的所有图片数量
let flatIndexBase = 0;
for (let i = 0; i < index; i++) {
flatIndexBase += rows[i]?.length || 0;
}
return (
<div style={{ ...style, paddingBottom: '32px' }} className="flex gap-4">
{row.map((image, imageIndex) => renderImageCell(image, flatIndexBase + imageIndex))}
</div>
);
};
if (!filteredImages.length) {
return (
<div ref={containerRef} className="flex items-center justify-center h-full text-gray-500 dark:text-gray-400">
<div className="text-center">
<p className="text-lg mb-2">暂无图片</p>
<p className="text-sm">请添加素材库或调整搜索条件</p>
</div>
</div>
);
}
// Worker 正在计算中,显示加载状态(只在容器宽度已知且 Worker 已触发时)
if (useWorker && rows.length === 0 && filteredImages.length > 0 && containerWidth > 0) {
return (
<div ref={containerRef} className="flex items-center justify-center h-full text-gray-500 dark:text-gray-400">
<div className="text-center">
<div className="animate-spin w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full mx-auto mb-2"></div>
<p className="text-sm">正在计算布局...</p>
</div>
</div>
);
}
// 等待容器宽度初始化
if (!containerWidth && filteredImages.length > 0) {
return (
<div ref={containerRef} className="h-full overflow-hidden" />
);
}
return (
<div ref={containerRef} className="h-full overflow-hidden">
<PhotoProvider
images={providerImages}
visible={photoIndex >= 0}
onClose={() => setPhotoIndex(-1)}
index={photoIndex}
onIndexChange={setPhotoIndex}
>
{useVirtualScroll ? (
/* 虚拟滚动模式(>500张图片) */
<List
ref={listRef}
height={containerHeight || 600}
width={containerWidth + 32}
itemCount={rows.length}
itemSize={getRowHeight}
className="p-4"
overscanCount={3}
>
{renderRow}
</List>
) : (
/* 普通渲染模式(≤500张图片) */
<div className="h-full overflow-y-auto p-4">
<div className="space-y-8">
{rows.map((row, rowIndex) => {
let flatIndexBase = 0;
for (let i = 0; i < rowIndex; i++) {
flatIndexBase += rows[i]?.length || 0;
}
return (
<div key={rowIndex} className="flex gap-4">
{row.map((image, imageIndex) => renderImageCell(image, flatIndexBase + imageIndex))}
</div>
);
})}
</div>
</div>
)}
</PhotoProvider>
{/* 文件查看器 */}
{viewerFile && (
<FileViewer
file={viewerFile}
libraryId={currentLibraryId}
onClose={() => setViewerFile(null)}
/>
)}
</div>
);
}
export default ImageWaterfall;
+310
View File
@@ -0,0 +1,310 @@
import { useEffect, useRef, useState, useCallback } from 'react';
import { Pause, Play } from 'lucide-react';
import useStore from '../store/useStore';
import { imageAPI, scanAPI } from '../services/api';
import ImageWaterfall from './ImageWaterfall';
import Dashboard from './Dashboard';
function MainContent() {
const {
currentLibraryId,
searchKeywords,
filters,
selectedFolder,
setImages,
setTotalImageCount,
scanProgress,
scanStartTime
} = useStore();
// 使用 ref 跟踪最新的请求
const loadingRequestRef = useRef(0);
// 文件夹切换防抖
const folderDebounceRef = useRef(null);
const [isLoadingImages, setIsLoadingImages] = useState(false);
// 计算预估剩余时间(优先使用后端提供的estimatedTimeLeft)
const getEstimatedTime = () => {
if (!scanProgress || scanProgress.current === 0) {
return null;
}
// 优先使用后端提供的预估时间
if (scanProgress.estimatedTimeLeft !== undefined) {
const seconds = scanProgress.estimatedTimeLeft;
if (seconds < 1) return '即将完成';
if (seconds < 60) return `剩余约 ${seconds} 秒`;
if (seconds < 3600) {
const min = Math.floor(seconds / 60);
const sec = seconds % 60;
return sec > 0 ? `剩余约 ${min} 分 ${sec} 秒` : `剩余约 ${min} 分钟`;
}
const hrs = Math.floor(seconds / 3600);
const min = Math.floor((seconds % 3600) / 60);
return min > 0 ? `剩余约 ${hrs} 小时 ${min} 分钟` : `剩余约 ${hrs} 小时`;
}
// 降级:使用前端计算
if (!scanStartTime) return null;
const elapsed = Date.now() - scanStartTime;
const progress = scanProgress.current / scanProgress.total;
if (progress === 0) return null;
const remaining = (elapsed / progress) - elapsed;
const seconds = Math.ceil(remaining / 1000);
if (seconds < 60) return `剩余约 ${seconds} 秒`;
if (seconds < 3600) {
const min = Math.floor(seconds / 60);
const sec = seconds % 60;
return sec > 0 ? `剩余约 ${min} 分 ${sec} 秒` : `剩余约 ${min} 分钟`;
}
const hrs = Math.floor(seconds / 3600);
const min = Math.floor((seconds % 3600) / 60);
return min > 0 ? `剩余约 ${hrs} 小时 ${min} 分钟` : `剩余约 ${hrs} 小时`;
};
// 使用 ref 追踪上次的 libraryId,避免重复加载
const lastLibraryIdRef = useRef(null);
// 扫描控制
const [scanPaused, setScanPaused] = useState(false);
const [isStoppingOrResuming, setIsStoppingOrResuming] = useState(false);
useEffect(() => {
if (currentLibraryId) {
// 文件夹切换使用防抖(30ms),避免快速点击导致多次请求
if (folderDebounceRef.current) {
clearTimeout(folderDebounceRef.current);
}
folderDebounceRef.current = setTimeout(() => {
loadImages();
}, selectedFolder !== null ? 30 : 0); // 选择文件夹时防抖,清空时立即加载
// 只在切换素材库时加载文件夹和总数
if (lastLibraryIdRef.current !== currentLibraryId) {
loadFolders();
lastLibraryIdRef.current = currentLibraryId;
}
}
return () => {
if (folderDebounceRef.current) {
clearTimeout(folderDebounceRef.current);
}
};
}, [currentLibraryId, searchKeywords, filters, selectedFolder]);
const loadImages = useCallback(async () => {
if (!currentLibraryId) return;
// 递增请求ID
const requestId = ++loadingRequestRef.current;
// Optimization: If no folder selected and no search/filters, do NOT fetch images
// This prevents loading all images when showing Dashboard
if (!selectedFolder && !searchKeywords && filters.formats.length === 0) {
if (requestId === loadingRequestRef.current) {
setImages([]); // Clear images to save memory
setIsLoadingImages(false);
}
return;
}
setIsLoadingImages(true);
try {
const params = {
keywords: searchKeywords,
...filters
};
// 只有选中了文件夹才添加 folder 参数
if (selectedFolder) {
params.folder = selectedFolder;
}
const response = await imageAPI.search(currentLibraryId, params);
// 只有当这是最新的请求时才更新状态
if (requestId === loadingRequestRef.current) {
setImages(response.data.images);
// 无筛选条件时,同步更新总数
if (!selectedFolder && !searchKeywords) {
setTotalImageCount(response.data.images.length);
}
}
} catch (error) {
// 只有当这是最新的请求时才显示错误
if (requestId === loadingRequestRef.current) {
console.error('Error loading images:', error);
}
} finally {
if (requestId === loadingRequestRef.current) {
setIsLoadingImages(false);
}
}
}, [currentLibraryId, searchKeywords, filters, selectedFolder, setImages, setTotalImageCount]);
const loadFolders = async () => {
if (!currentLibraryId) return;
try {
const response = await imageAPI.getFolders(currentLibraryId);
useStore.getState().setFolders(response.data.folders);
} catch (error) {
console.error('Error loading folders:', error);
}
};
// 停止扫描
const handleStopScan = async () => {
if (!currentLibraryId || isStoppingOrResuming) return;
setIsStoppingOrResuming(true);
try {
await scanAPI.stop(currentLibraryId);
setScanPaused(true);
} catch (error) {
console.error('Error stopping scan:', error);
} finally {
setIsStoppingOrResuming(false);
}
};
// 继续扫描
const handleResumeScan = async () => {
if (!currentLibraryId || isStoppingOrResuming) return;
setIsStoppingOrResuming(true);
try {
if (scanProgress?.needsRescan) {
// 应用重启后的恢复:使用增量同步
console.log('🔄 使用增量同步恢复扫描');
await scanAPI.sync(currentLibraryId);
} else {
// 正常继续扫描
await scanAPI.resume(currentLibraryId);
}
setScanPaused(false);
} catch (error) {
console.error('Error resuming scan:', error);
} finally {
setIsStoppingOrResuming(false);
}
};
// 当扫描进度变化时同步暂停状态
useEffect(() => {
if (!scanProgress) {
setScanPaused(false);
} else if (scanProgress.isPaused) {
// 从 Sidebar/App 恢复的暂停状态
setScanPaused(true);
} else if (scanProgress.percent === 100) {
// 扫描完成时清除暂停状态
setScanPaused(false);
}
}, [scanProgress]);
return (
<div className="flex flex-col h-full bg-gray-50 dark:bg-gray-900">
{/* Scan Progress - 只有当有进度数据时才显示 */}
{scanProgress && (
<div className={`p-4 border-b ${scanPaused
? 'bg-yellow-50 dark:bg-yellow-900 border-yellow-200 dark:border-yellow-700'
: 'bg-blue-50 dark:bg-blue-900 border-blue-200 dark:border-blue-700'
}`}>
<div className="flex items-center justify-between mb-2">
<div className={`text-sm font-medium ${scanPaused
? 'text-yellow-700 dark:text-yellow-300'
: 'text-blue-700 dark:text-blue-300'
}`}>
{scanPaused
? '扫描已暂停'
: scanProgress?.status === 'preparing'
? '正在准备扫描...'
: '正在扫描素材库,期间请勿操作,会影响扫描速度'
}
</div>
<div className="flex items-center gap-2">
<span className={`text-sm ${scanPaused
? 'text-yellow-600 dark:text-yellow-400'
: 'text-blue-600 dark:text-blue-400'
}`}>
{scanProgress?.percent || 0}%
</span>
{/* 停止/继续按钮 */}
{(scanProgress?.canStop || scanPaused) && (
<button
onClick={scanPaused ? handleResumeScan : handleStopScan}
disabled={isStoppingOrResuming}
className={`p-1.5 rounded-md transition-colors ${scanPaused
? 'bg-green-500 hover:bg-green-600 text-white'
: 'bg-yellow-500 hover:bg-yellow-600 text-white'
} ${isStoppingOrResuming ? 'opacity-50 cursor-not-allowed' : ''}`}
title={scanPaused ? '继续扫描' : '暂停扫描'}
>
{isStoppingOrResuming ? (
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
) : scanPaused ? (
<Play className="w-4 h-4" />
) : (
<Pause className="w-4 h-4" />
)}
</button>
)}
</div>
</div>
<div className={`w-full rounded-full h-2 mb-2 ${scanPaused
? 'bg-yellow-200 dark:bg-yellow-800'
: 'bg-blue-200 dark:bg-blue-800'
}`}>
<div
className={`h-2 rounded-full transition-all duration-300 ${scanPaused
? 'bg-yellow-500'
: scanProgress?.status === 'preparing'
? 'bg-blue-400 animate-pulse'
: 'bg-blue-500'
}`}
style={{ width: `${scanProgress?.percent || 0}%` }}
/>
</div>
<div className={`flex items-center justify-between text-xs ${scanPaused
? 'text-yellow-600 dark:text-yellow-400'
: 'text-blue-600 dark:text-blue-400'
}`}>
<span>
{scanPaused
? scanProgress?.needsRescan
? `上次扫描中断于 ${scanProgress?.current || 0} 张,点击继续完成`
: `已处理 ${scanProgress?.current || 0} 张,剩余 ${scanProgress?.pendingCount || (scanProgress?.total - scanProgress?.current) || 0} 张待处理`
: scanProgress?.status === 'preparing'
? '正在初始化...'
: `已处理 ${scanProgress?.current || 0} / ${scanProgress?.total || 0} 张图片`
}
</span>
<span>
{scanPaused
? scanProgress?.needsRescan ? '需要继续' : '暂停中'
: (getEstimatedTime() || '扫描完成后将自动显示')
}
</span>
</div>
</div>
)}
{/* Content Area */}
<div className="flex-1 overflow-hidden">
{(!selectedFolder && !searchKeywords && filters.formats.length === 0) ? (
<Dashboard />
) : (
<ImageWaterfall />
)}
</div>
</div>
);
}
export default MainContent;
+553
View File
@@ -0,0 +1,553 @@
import { useState, useEffect } from 'react';
import { Copy, Download, Check, FolderDown, ArrowLeft } from 'lucide-react';
import useStore from '../store/useStore';
import { imageAPI } from '../services/api';
import JSZip from 'jszip';
function RightPanel() {
const { selectedImage, selectedImages, currentLibraryId, selectedFolder, images, setMobileView, isResizingPanels, resizingSide } = useStore();
const [isMobile, setIsMobile] = useState(false);
const [imageUrl, setImageUrl] = useState(''); // 当前显示的图片URL
const [isLoadingOriginal, setIsLoadingOriginal] = useState(false);
const [copied, setCopied] = useState(false);
const [imageCopied, setImageCopied] = useState(false);
const [isExporting, setIsExporting] = useState(false);
const [exportProgress, setExportProgress] = useState(0);
const [isExportingFolder, setIsExportingFolder] = useState(false);
const [folderExportProgress, setFolderExportProgress] = useState(0);
// 判断是单选还是多选
const isMultiSelect = selectedImages.length > 0;
const displayImage = isMultiSelect ? selectedImages[0] : selectedImage;
// 检测移动端
useEffect(() => {
const checkMobile = () => {
setIsMobile(window.innerWidth < 768);
};
checkMobile();
window.addEventListener('resize', checkMobile);
return () => window.removeEventListener('resize', checkMobile);
}, []);
// 图片加载策略:先显示缩略图,后台加载原图;拖动右侧面板时只显示缩略图
useEffect(() => {
if (!selectedImage || !currentLibraryId) {
setImageUrl('');
return;
}
// 1. 立即显示缩略图
const thumbnailUrl = getThumbnailUrl();
setImageUrl(thumbnailUrl);
setIsLoadingOriginal(true);
// 如果正在拖动任一面板,则先不加载原图,降低主线程和解码压力
if (isResizingPanels) {
setIsLoadingOriginal(false);
return;
}
// 2. 后台预加载原图
const originalUrl = getOriginalUrl();
const img = new Image();
img.onload = () => {
// 原图加载完成,切换到原图
setImageUrl(originalUrl);
setIsLoadingOriginal(false);
};
img.onerror = () => {
// 原图加载失败,保持显示缩略图
console.error('Failed to load original image');
setIsLoadingOriginal(false);
};
img.src = originalUrl;
// 清理函数
return () => {
img.onload = null;
img.onerror = null;
};
}, [selectedImage, currentLibraryId, isResizingPanels, resizingSide]);
if (!selectedImage && selectedImages.length === 0) {
return (
<div className="w-full border-l border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 flex items-center justify-center">
<p className="text-gray-400 dark:text-gray-500 text-sm">选择图片查看详情</p>
</div>
);
}
const getThumbnailUrl = () => {
if (!currentLibraryId || !selectedImage.thumbnail_path) return '';
// Handle both forward and backslash
const filename = selectedImage.thumbnail_path.replace(/\\/g, '/').split('/').pop();
return imageAPI.getThumbnailUrl(currentLibraryId, '200', filename);
};
const getOriginalUrl = () => {
if (!currentLibraryId || !selectedImage.path) return '';
return imageAPI.getOriginalUrl(currentLibraryId, selectedImage.path);
};
// 复制图片到剪贴板(支持粘贴到聊天软件和文件管理器)
const copyImageToClipboard = async () => {
try {
// 获取原图URL
const imageUrl = imageAPI.getOriginalUrl(currentLibraryId, selectedImage.path);
// 获取图片数据
const response = await fetch(imageUrl);
const blob = await response.blob();
// 创建临时图片元素
const img = new Image();
const loadPromise = new Promise((resolve, reject) => {
img.onload = resolve;
img.onerror = reject;
});
img.src = URL.createObjectURL(blob);
await loadPromise;
// 使用 canvas 转换为 PNG
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
// 转换为 PNG blob
canvas.toBlob(async (pngBlob) => {
try {
// 创建包含多种格式的剪贴板项
const clipboardItem = new ClipboardItem({
'image/png': pngBlob,
// 添加 HTML 格式(支持更多粘贴场景)
'text/html': new Blob(
[`<img src="${imageUrl}" alt="${selectedImage.filename}">`],
{ type: 'text/html' }
),
// 添加纯文本格式(文件路径)
'text/plain': new Blob(
[imageUrl],
{ type: 'text/plain' }
)
});
await navigator.clipboard.write([clipboardItem]);
setImageCopied(true);
setTimeout(() => setImageCopied(false), 2000);
} catch (err) {
console.error('写入剪贴板失败:', err);
// 如果多格式失败,尝试只复制图像
try {
await navigator.clipboard.write([
new ClipboardItem({ 'image/png': pngBlob })
]);
setImageCopied(true);
setTimeout(() => setImageCopied(false), 2000);
} catch (fallbackErr) {
console.error('备用方案也失败:', fallbackErr);
alert('复制失败,请重试');
}
}
}, 'image/png');
// 清理
URL.revokeObjectURL(img.src);
} catch (error) {
console.error('复制图片失败:', error);
alert('复制图片失败,请重试');
}
};
// 批量复制图片
const copyMultipleImages = async () => {
try {
const imagesToCopy = isMultiSelect ? selectedImages : [selectedImage];
if (imagesToCopy.length === 1) {
// 单张图片:直接复制
await copyImageToClipboard();
return;
}
// 多张图片:浏览器限制,只能复制为 HTML 格式(包含多个 img 标签)
// 这样粘贴到支持 HTML 的应用时,会显示为多张图片
// 加载所有图片并转换为 base64
const imageDataList = await Promise.all(
imagesToCopy.map(async (img) => {
const imageUrl = imageAPI.getOriginalUrl(currentLibraryId, img.path);
const response = await fetch(imageUrl);
const blob = await response.blob();
// 转换为 base64
return new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => {
resolve({
dataUrl: reader.result,
filename: img.filename
});
};
reader.readAsDataURL(blob);
});
})
);
// 创建 HTML 格式(多个图片)
const htmlContent = imageDataList.map(({ dataUrl, filename }) =>
`<img src="${dataUrl}" alt="${filename}" style="display:block; margin:10px 0;">`
).join('\n');
// 创建纯文本格式(文件名列表)
const textContent = imagesToCopy.map(img => img.filename).join('\n');
try {
// 尝试写入多种格式
await navigator.clipboard.write([
new ClipboardItem({
'text/html': new Blob([htmlContent], { type: 'text/html' }),
'text/plain': new Blob([textContent], { type: 'text/plain' })
})
]);
setImageCopied(true);
setTimeout(() => setImageCopied(false), 2000);
} catch (err) {
console.error('写入剪贴板失败:', err);
alert(`复制失败。\n\n提示:浏览器限制,多张图片会以 HTML 格式复制。\n可粘贴到 Word、富文本编辑器等。\n\n如需单独使用,请使用"导出"功能。`);
}
} catch (error) {
console.error('复制图片失败:', error);
alert('复制图片失败,请重试');
}
};
// 批量导出图片(打包成 ZIP)
const exportMultipleImages = async () => {
setIsExporting(true);
try {
const imagesToExport = isMultiSelect ? selectedImages : [selectedImage];
if (imagesToExport.length === 1) {
// 单张图片直接下载
const url = imageAPI.getOriginalUrl(currentLibraryId, imagesToExport[0].path);
const link = document.createElement('a');
link.href = url;
link.download = imagesToExport[0].filename;
link.target = '_blank';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} else {
// 多张图片:打包成 ZIP
const zip = new JSZip();
const folder = zip.folder('images');
setExportProgress(0);
// 下载所有图片并添加到 ZIP
for (let i = 0; i < imagesToExport.length; i++) {
const img = imagesToExport[i];
const url = imageAPI.getOriginalUrl(currentLibraryId, img.path);
try {
const response = await fetch(url);
const blob = await response.blob();
// 添加到 ZIP,使用原文件名
folder.file(img.filename, blob);
// 更新进度
const progress = Math.round(((i + 1) / imagesToExport.length) * 90); // 90% 用于下载
setExportProgress(progress);
console.log(`已添加: ${img.filename} (${i + 1}/${imagesToExport.length})`);
} catch (error) {
console.error(`下载失败: ${img.filename}`, error);
}
}
// 生成 ZIP 文件
setExportProgress(95);
console.log('正在生成 ZIP 文件...');
const zipBlob = await zip.generateAsync({
type: 'blob',
compression: 'DEFLATE',
compressionOptions: { level: 6 }
});
// 下载 ZIP 文件
setExportProgress(100);
const link = document.createElement('a');
link.href = URL.createObjectURL(zipBlob);
link.download = `FlyPic_导出_${imagesToExport.length}张_${Date.now()}.zip`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
console.log('导出完成!');
}
} catch (error) {
console.error('导出失败:', error);
alert('导出失败,请重试');
} finally {
setIsExporting(false);
}
};
// 导出当前文件夹的所有图片
const exportCurrentFolder = async () => {
if (!selectedFolder) {
alert('请先选择一个文件夹');
return;
}
setIsExportingFolder(true);
setFolderExportProgress(0);
try {
// 获取当前文件夹下的所有图片
const folderImages = images.filter(img => {
// 检查图片是否在当前文件夹或其子文件夹中
return img.folder && img.folder.startsWith(selectedFolder);
});
if (folderImages.length === 0) {
alert('当前文件夹没有图片');
return;
}
// 创建 ZIP
const zip = new JSZip();
const folderName = selectedFolder.split('/').pop() || 'images';
const folder = zip.folder(folderName);
// 下载所有图片并添加到 ZIP
for (let i = 0; i < folderImages.length; i++) {
const img = folderImages[i];
const url = imageAPI.getOriginalUrl(currentLibraryId, img.path);
try {
const response = await fetch(url);
const blob = await response.blob();
// 保持相对路径结构
const relativePath = img.folder.replace(selectedFolder, '').replace(/^\//, '');
const filePath = relativePath ? `${relativePath}/${img.filename}` : img.filename;
folder.file(filePath, blob);
// 更新进度
const progress = Math.round(((i + 1) / folderImages.length) * 90);
setFolderExportProgress(progress);
console.log(`已添加: ${filePath} (${i + 1}/${folderImages.length})`);
} catch (error) {
console.error(`下载失败: ${img.filename}`, error);
}
}
// 生成 ZIP 文件
setFolderExportProgress(95);
console.log('正在生成 ZIP 文件...');
const zipBlob = await zip.generateAsync({
type: 'blob',
compression: 'DEFLATE',
compressionOptions: { level: 6 }
});
// 下载 ZIP 文件
setFolderExportProgress(100);
const link = document.createElement('a');
link.href = URL.createObjectURL(zipBlob);
link.download = `${folderName}_${folderImages.length}张_${Date.now()}.zip`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
console.log('文件夹导出完成!');
} catch (error) {
console.error('导出文件夹失败:', error);
alert('导出文件夹失败,请重试');
} finally {
setIsExportingFolder(false);
}
};
const formatFileSize = (bytes) => {
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
};
const formatDate = (timestamp) => {
return new Date(timestamp).toLocaleString('zh-CN');
};
return (
<div className="w-full border-l border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 flex flex-col h-full">
{/* 移动端返回按钮 */}
{isMobile && (
<div className="p-4 border-b border-gray-200 dark:border-gray-700 flex items-center">
<button
onClick={() => setMobileView('main')}
className="flex items-center gap-2 text-gray-700 dark:text-gray-300 hover:text-blue-500"
>
<ArrowLeft className="w-5 h-5" />
<span className="text-sm font-medium">返回</span>
</button>
</div>
)}
{/* Progressive Image Preview */}
<div className="p-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
<div className="w-full aspect-square bg-gray-100 dark:bg-gray-700 rounded-lg overflow-hidden relative">
<img
src={imageUrl}
alt={displayImage.filename}
decoding="async"
className={`w-full h-full object-contain transition-opacity duration-300 ${
isLoadingOriginal ? 'opacity-75' : 'opacity-100'
}`}
/>
{isLoadingOriginal && (
<div className="absolute top-2 right-2 bg-blue-500 text-white text-xs px-2 py-1 rounded">
加载原图中...
</div>
)}
</div>
</div>
{/* Image Info - 可滚动区域 */}
<div className="flex-1 overflow-y-auto p-4 space-y-4 min-h-0">
<div>
<h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">基本信息</h3>
<div className="space-y-2 text-sm">
<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.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.modified_at)}</p>
</div>
<div>
<span className="text-gray-500 dark:text-gray-400">路径:</span>
<p className="text-gray-900 dark:text-gray-100 text-xs break-all">{selectedImage.path}</p>
</div>
</div>
</div>
</div>
{/* Actions - 仅桌面端显示 */}
{!isMobile && (
<div className="p-4 border-t border-gray-200 dark:border-gray-700 space-y-2 flex-shrink-0">
{/* 复制按钮 */}
<button
onClick={copyMultipleImages}
className={`w-full flex items-center justify-center gap-2 px-4 py-2 rounded-lg transition-all ${
imageCopied
? 'bg-green-500 text-white'
: 'bg-blue-500 text-white hover:bg-blue-600'
}`}
>
{imageCopied ? (
<>
<Check className="w-4 h-4" />
<span>已复制{isMultiSelect ? ` ${selectedImages.length} 张` : ''}</span>
</>
) : (
<>
<Copy className="w-4 h-4" />
<span>复制图片{isMultiSelect ? ` (${selectedImages.length})` : ''}</span>
</>
)}
</button>
{/* 导出按钮 */}
<button
onClick={exportMultipleImages}
disabled={isExporting}
className="w-full flex flex-col items-center justify-center gap-2 px-4 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
<div className="flex items-center gap-2">
<Download className="w-4 h-4" />
<span>
{isExporting
? `打包中... ${exportProgress}%`
: `导出图片${isMultiSelect ? ` (${selectedImages.length})` : ''}`
}
</span>
</div>
{isExporting && isMultiSelect && (
<div className="w-full bg-gray-300 dark:bg-gray-600 rounded-full h-1.5 mt-1">
<div
className="bg-blue-500 h-1.5 rounded-full transition-all duration-300"
style={{ width: `${exportProgress}%` }}
/>
</div>
)}
</button>
{/* 导出文件夹按钮 */}
{selectedFolder && (
<button
onClick={exportCurrentFolder}
disabled={isExportingFolder}
className="w-full flex flex-col items-center justify-center gap-2 px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
<div className="flex items-center gap-2">
<FolderDown className="w-4 h-4" />
<span>
{isExportingFolder
? `打包文件夹... ${folderExportProgress}%`
: '导出当前文件夹'
}
</span>
</div>
{isExportingFolder && (
<div className="w-full bg-purple-300 rounded-full h-1.5 mt-1">
<div
className="bg-white h-1.5 rounded-full transition-all duration-300"
style={{ width: `${folderExportProgress}%` }}
/>
</div>
)}
</button>
)}
</div>
)}
</div>
);
}
export default RightPanel;
+601
View File
@@ -0,0 +1,601 @@
import { useState, useMemo, useEffect, useRef } from 'react';
import { Folder, Search, ChevronRight, ChevronDown, X, Trash2, ChevronsRight, ChevronsDown } from 'lucide-react';
import useStore from '../store/useStore';
import { libraryAPI, scanAPI, imageAPI } from '../services/api';
// 检查素材库是否有暂停的扫描
const checkPausedScan = async (libraryId) => {
try {
const response = await scanAPI.getStatus(libraryId);
return response.data;
} catch (error) {
return null;
}
};
function Sidebar() {
const {
libraries,
currentLibraryId,
folders,
selectedFolder,
totalImageCount,
setCurrentLibrary,
setSelectedFolder,
addLibrary,
removeLibrary
} = useStore();
const [showAddLibrary, setShowAddLibrary] = useState(false);
const [newLibraryName, setNewLibraryName] = useState('');
const [newLibraryPath, setNewLibraryPath] = useState('');
const [folderSearch, setFolderSearch] = useState('');
const [localFolderSearch, setLocalFolderSearch] = useState(''); // 本地输入值
const [expandedFolders, setExpandedFolders] = useState(new Set());
const [isAdding, setIsAdding] = useState(false);
const [isSwitching, setIsSwitching] = useState(false);
const folderSearchDebounceRef = useRef(null);
// 文件夹搜索防抖(300ms)
const handleFolderSearchChange = (value) => {
setLocalFolderSearch(value);
if (folderSearchDebounceRef.current) {
clearTimeout(folderSearchDebounceRef.current);
}
folderSearchDebounceRef.current = setTimeout(() => {
setFolderSearch(value);
}, 300);
};
// 清理定时器
useEffect(() => {
return () => {
if (folderSearchDebounceRef.current) {
clearTimeout(folderSearchDebounceRef.current);
}
};
}, []);
const handleAddLibrary = async () => {
if (!newLibraryName.trim()) {
alert('请输入素材库名称');
return;
}
if (!newLibraryPath.trim()) {
alert('请输入文件夹路径');
return;
}
setIsAdding(true);
try {
// 1. 添加素材库
console.log('📝 添加素材库...');
const response = await libraryAPI.add(newLibraryName.trim(), newLibraryPath.trim());
const newLibId = response.data.id;
const hasExistingIndex = response.data.hasExistingIndex;
addLibrary({
id: newLibId,
name: newLibraryName.trim(),
path: newLibraryPath.trim()
});
// 2. 关闭表单
setNewLibraryName('');
setNewLibraryPath('');
setShowAddLibrary(false);
setIsAdding(false); // 立即释放按钮
// 3. 切换到新素材库
console.log('🔄 切换到新素材库...');
await libraryAPI.setCurrent(newLibId);
setCurrentLibrary(newLibId);
setSelectedFolder(null);
// 4. 清空当前显示
useStore.getState().setImages([]);
useStore.getState().setFolders([]);
useStore.getState().setSelectedImage(null);
useStore.getState().setTotalImageCount(0); // 清空总数
// 5. 显示初始进度(立即显示,不等待后端)
useStore.getState().setScanProgress({
libraryId: newLibId,
current: 0,
total: 0,
percent: 0,
status: 'preparing'
});
// 6. 如果有已有索引,先快速加载数据库中的数据
if (hasExistingIndex) {
console.log('检测到已有索引,先加载现有数据...');
try {
const [foldersRes, countRes] = await Promise.all([
imageAPI.getFolders(newLibId),
imageAPI.getCount(newLibId)
]);
useStore.getState().setFolders(foldersRes.data.folders);
useStore.getState().setTotalImageCount(countRes.data.count);
console.log('✅ 已加载现有数据');
} catch (err) {
console.warn('⚠️ 加载现有数据失败:', err);
}
}
// 7. 开始异步扫描(不等待,Socket.IO 会推送进度)
console.log('🔍 开始异步扫描...');
if (hasExistingIndex) {
console.log('执行增量同步,检测变化...');
scanAPI.sync(newLibId, false); // wait=false,异步执行
} else {
console.log('首次添加,执行全量扫描...');
scanAPI.fullScan(newLibId, false); // wait=false,异步执行
}
// 扫描在后台进行,Socket.IO 会推送进度和完成事件
// App.jsx 中的 scanComplete 监听器会自动刷新数据
console.log('✅ 扫描已启动,请等待进度显示...');
} catch (error) {
console.error('❌ Error adding library:', error);
alert('添加素材库失败: ' + error.message);
useStore.getState().setScanProgress(null);
setIsAdding(false);
}
};
const handleLibraryClick = async (libraryId) => {
if (libraryId === currentLibraryId) return;
setIsSwitching(true);
try {
// 切换前清理当前素材库的状态
useStore.getState().setScanProgress(null);
useStore.getState().setSelectedImage(null);
setSelectedFolder(null);
// 并行执行:切换素材库 + 预加载数据
const [, foldersRes, imagesRes] = await Promise.all([
libraryAPI.setCurrent(libraryId),
imageAPI.getFolders(libraryId),
imageAPI.search(libraryId, {})
]);
// 更新状态
setCurrentLibrary(libraryId);
useStore.getState().setFolders(foldersRes.data.folders);
useStore.getState().setImages(imagesRes.data.images);
useStore.getState().setTotalImageCount(imagesRes.data.images.length);
// 后台检查新素材库是否有暂停的扫描(不阻塞主流程)
checkPausedScan(libraryId).then(scanStatus => {
if (scanStatus && scanStatus.status === 'paused') {
if (scanStatus.needsRescan) {
useStore.getState().setScanProgress({
...scanStatus.progress,
libraryId,
canStop: true,
isPaused: true,
pendingCount: scanStatus.progress?.total - scanStatus.progress?.current || 0,
needsRescan: true
});
console.log(`⏸️ 发现中断的扫描,需要继续完成`);
} else if (scanStatus.pendingCount > 0) {
useStore.getState().setScanProgress({
...scanStatus.progress,
libraryId,
canStop: true,
isPaused: true,
pendingCount: scanStatus.pendingCount
});
console.log(`⏸️ 发现暂停的扫描,待处理: ${scanStatus.pendingCount} 张`);
}
}
}).catch(() => { }); // 忽略状态检查错误
} catch (error) {
console.error('Error setting current library:', error);
alert('切换素材库失败: ' + error.message);
} finally {
setIsSwitching(false);
}
};
const handleDeleteLibrary = async () => {
if (!currentLibraryId) return;
const currentLib = libraries.find(lib => lib.id === currentLibraryId);
if (!currentLib) return;
// 确认删除
const confirmDelete = confirm(
`确定要删除素材库"${currentLib.name}"吗?\n\n` +
`路径: ${currentLib.path}\n\n` +
`⚠️ 注意:\n` +
`• 将删除索引数据并释放数据库连接\n` +
`• 不会删除原始图片文件\n` +
`• .flypic 文件夹将保留,您可以手动删除`
);
if (!confirmDelete) return;
try {
// 删除素材库(会自动关闭数据库连接)
await libraryAPI.delete(currentLibraryId);
removeLibrary(currentLibraryId);
// Clear UI state
useStore.getState().setImages([]);
useStore.getState().setFolders([]);
useStore.getState().setSelectedImage(null);
useStore.getState().setSelectedFolder(null);
// Switch to first available library if exists
const remainingLibs = libraries.filter(lib => lib.id !== currentLibraryId);
if (remainingLibs.length > 0) {
const firstLib = remainingLibs[0];
await libraryAPI.setCurrent(firstLib.id);
setCurrentLibrary(firstLib.id);
}
// 静默成功,不弹窗
console.log(`✅ 素材库已删除: ${currentLib.name}`);
console.log(`数据库连接已释放,可手动删除: ${currentLib.path}\\.flypic`);
} catch (error) {
console.error('Error deleting library:', error);
alert('删除素材库失败: ' + error.message);
}
};
const toggleFolder = (folderPath) => {
const newExpanded = new Set(expandedFolders);
if (newExpanded.has(folderPath)) {
newExpanded.delete(folderPath);
} else {
newExpanded.add(folderPath);
}
setExpandedFolders(newExpanded);
};
// 收集所有文件夹路径
const getAllFolderPaths = (folderList) => {
const paths = [];
const traverse = (folders) => {
folders.forEach(folder => {
if (folder.children && folder.children.length > 0) {
paths.push(folder.path);
traverse(folder.children);
}
});
};
traverse(folderList);
return paths;
};
// 全部展开
const expandAll = () => {
const allPaths = getAllFolderPaths(filteredFolders.length > 0 ? filteredFolders : folders);
setExpandedFolders(new Set(allPaths));
};
// 全部折叠
const collapseAll = () => {
setExpandedFolders(new Set());
};
// 判断是否全部展开
const isAllExpanded = () => {
const allPaths = getAllFolderPaths(filteredFolders.length > 0 ? filteredFolders : folders);
return allPaths.length > 0 && allPaths.every(path => expandedFolders.has(path));
};
// 使用 useMemo 缓存过滤结果(支持多关键词搜索)
const filteredFolders = useMemo(() => {
if (!folderSearch) return folders;
// 分割搜索词,支持空格分隔的多个关键词
const keywords = folderSearch
.trim()
.toLowerCase()
.split(/\s+/)
.filter(k => k.length > 0);
if (keywords.length === 0) return folders;
const pathsToExpand = [];
const filterRecursive = (folderList) => {
return folderList.reduce((acc, folder) => {
const folderName = folder.name.toLowerCase();
const folderPath = folder.path.toLowerCase();
// 检查是否所有关键词都匹配(AND 逻辑)
const nameMatches = keywords.every(keyword =>
folderName.includes(keyword)
);
const pathMatches = keywords.every(keyword =>
folderPath.includes(keyword)
);
let filteredChildren = [];
if (folder.children && folder.children.length > 0) {
filteredChildren = filterRecursive(folder.children);
}
// 如果文件夹名称匹配,或者路径匹配,或者有子文件夹匹配,则包含此文件夹
if (nameMatches || pathMatches || filteredChildren.length > 0) {
acc.push({
...folder,
children: filteredChildren
});
// 记录需要展开的路径
if (filteredChildren.length > 0) {
pathsToExpand.push(folder.path);
}
}
return acc;
}, []);
};
const result = filterRecursive(folders);
// 使用 setTimeout 来更新展开状态
if (pathsToExpand.length > 0) {
setTimeout(() => {
setExpandedFolders(prev => {
const newSet = new Set(prev);
pathsToExpand.forEach(path => newSet.add(path));
return newSet;
});
}, 0);
}
return result;
}, [folders, folderSearch]);
// 点击箭头图标:只展开/折叠,不选中
const handleToggleClick = (e, folderPath) => {
e.stopPropagation(); // 阻止事件冒泡
toggleFolder(folderPath);
};
// 点击文件夹主体:首次选中,再次点击展开/折叠
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 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;
return (
<div key={folder.path}>
<div
className={`flex items-center px-3 py-2 cursor-pointer rounded-md transition-colors ${isSelected
? 'bg-blue-50 dark:bg-blue-900'
: 'hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
style={{ paddingLeft: `${level * 16 + 12}px` }}
onClick={() => handleFolderClick(folder)}
>
{/* 展开/折叠图标 - 独立点击区域 */}
{hasChildren ? (
<div
className="flex items-center justify-center w-5 h-5 mr-1 cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 rounded"
onClick={(e) => handleToggleClick(e, folder.path)}
>
{isExpanded ? (
<ChevronDown className="w-4 h-4 text-gray-500" />
) : (
<ChevronRight className="w-4 h-4 text-gray-500" />
)}
</div>
) : (
<div className="w-5 mr-1" />
)}
{/* 文件夹图标 */}
<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>
{/* 图片数量 */}
<span className="text-xs text-gray-400 ml-2 flex-shrink-0">{folder.image_count}</span>
</div>
{hasChildren && isExpanded && renderFolderTree(folder.children, level + 1)}
</div>
);
});
};
return (
<div className="w-full h-full border-r border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 flex flex-col">
{/* Library Management */}
<div className="p-4 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center justify-between mb-3">
<h2 className="text-sm font-semibold text-gray-700 dark:text-gray-300">素材库</h2>
</div>
{/* Library Selector with Delete Button */}
<div className="flex gap-2">
<div className="relative flex-1">
<select
value={currentLibraryId || ''}
onChange={(e) => {
const value = e.target.value;
if (value === '__add__') {
setShowAddLibrary(true);
} else if (value) {
handleLibraryClick(value);
}
}}
disabled={isSwitching}
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 appearance-none cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
style={{ paddingRight: '2rem' }}
>
{libraries.length === 0 && (
<option value="">暂无素材库</option>
)}
{libraries.map((library) => (
<option key={library.id} value={library.id}>
{library.name}
</option>
))}
<option value="__add__" style={{ borderTop: '1px solid #ccc' }}>
+ 添加新素材库
</option>
</select>
<ChevronDown className="absolute right-2 top-2.5 w-4 h-4 text-gray-400 pointer-events-none" />
</div>
{currentLibraryId && libraries.length > 0 && (
<button
onClick={handleDeleteLibrary}
className="px-3 py-2 border border-red-300 dark:border-red-600 rounded-lg hover:bg-red-50 dark:hover:bg-red-900 text-red-600 dark:text-red-400 transition-colors"
title="删除当前素材库"
>
<Trash2 className="w-4 h-4" />
</button>
)}
</div>
{/* Add Library Form */}
{showAddLibrary && (
<div className="mt-3 p-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700">
<div className="flex items-center justify-between mb-2">
<h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">添加素材库</h3>
<button
onClick={() => setShowAddLibrary(false)}
className="p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-600"
>
<X className="w-4 h-4 text-gray-500" />
</button>
</div>
<div className="space-y-2">
<input
type="text"
placeholder="素材库名称"
value={newLibraryName}
onChange={(e) => setNewLibraryName(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleAddLibrary()}
autoFocus
className="w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"
/>
<input
type="text"
placeholder="文件夹路径(例如:C:\Users\Pictures)"
value={newLibraryPath}
onChange={(e) => setNewLibraryPath(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleAddLibrary()}
className="w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"
/>
<div className="flex gap-2">
<button
onClick={() => setShowAddLibrary(false)}
className="flex-1 px-3 py-1.5 border border-gray-300 dark:border-gray-600 rounded text-sm hover:bg-gray-100 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300"
>
取消
</button>
<button
onClick={handleAddLibrary}
disabled={isAdding}
className="flex-1 px-3 py-1.5 bg-blue-500 text-white rounded text-sm hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"
>
{isAdding ? '添加中...' : '添加'}
</button>
</div>
</div>
</div>
)}
</div>
{/* Folder Tree */}
<div className="flex-1 overflow-y-auto p-4">
<div className="mb-3 space-y-2">
<div className="flex gap-2">
<div className="relative flex-1">
<Search className="absolute left-2 top-2 w-4 h-4 text-gray-400" />
<input
type="text"
placeholder="搜索文件夹(支持多关键词)..."
value={localFolderSearch}
onChange={(e) => handleFolderSearchChange(e.target.value)}
className="w-full pl-8 pr-3 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
/>
</div>
<button
onClick={isAllExpanded() ? collapseAll : expandAll}
className="px-2 py-1.5 border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-100 dark:hover:bg-gray-600 text-gray-600 dark:text-gray-400 transition-colors"
title={isAllExpanded() ? "折叠全部" : "展开全部"}
>
{isAllExpanded() ? (
<ChevronsRight className="w-4 h-4" />
) : (
<ChevronsDown className="w-4 h-4" />
)}
</button>
</div>
</div>
<div className="space-y-1">
{/* 全部图片选项 */}
<div
className={`flex items-center px-3 py-2 cursor-pointer rounded-md transition-colors ${selectedFolder === null
? 'bg-blue-50 dark:bg-blue-900'
: 'hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
onClick={() => setSelectedFolder(null)}
>
<div className="w-5 mr-1" />
<Folder className="w-4 h-4 mr-2 text-blue-500 flex-shrink-0" />
<span className="text-sm text-gray-700 dark:text-gray-300 font-medium flex-1">
全部图片
</span>
<span className="text-xs text-gray-500 dark:text-gray-400 ml-2">
{totalImageCount}
</span>
</div>
{/* 分隔线 */}
{(filteredFolders.length > 0 || folders.length > 0) && (
<div className="h-px bg-gray-200 dark:bg-gray-700 my-2" />
)}
{/* 文件夹树 */}
{filteredFolders.length > 0 ? (
renderFolderTree(filteredFolders)
) : folderSearch ? (
<div className="text-center py-8 text-gray-400 dark:text-gray-500 text-sm">
未找到匹配的文件夹
</div>
) : folders.length === 0 ? (
<div className="text-center py-8 text-gray-400 dark:text-gray-500 text-sm">
暂无文件夹
</div>
) : null}
</div>
</div>
</div>
);
}
export default Sidebar;
+388
View File
@@ -0,0 +1,388 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
#root {
width: 100vw;
height: 100vh;
overflow: hidden;
}
/* 暗色主题 - 纯黑灰色调 */
.dark {
--tw-bg-opacity: 1;
}
/* 背景色 - 纯黑灰 */
.dark .bg-gray-900 {
background-color: #0a0a0a !important;
}
.dark .bg-gray-800 {
background-color: #252525 !important; /* 侧边栏/顶部 - 稍微亮一些 */
}
.dark .bg-gray-700 {
background-color: #2a2a2a !important;
}
.dark .bg-gray-600 {
background-color: #3a3a3a !important;
}
.dark .bg-gray-500 {
background-color: #3a3a3a !important;
}
.dark .bg-gray-400 {
background-color: #4a4a4a !important;
}
.dark .bg-gray-300 {
background-color: #2a2a2a !important;
}
.dark .bg-gray-200:not(img):not(.image-container) {
background-color: #2a2a2a !important;
}
.dark .bg-gray-100 {
background-color: #1a1a1a !important;
}
.dark .bg-gray-50 {
background-color: #1a1a1a !important;
}
.dark .bg-white {
background-color: #1a1a1a !important;
}
/* 边框色 - 深灰 */
.dark .border-gray-700 {
border-color: #333333 !important;
}
.dark .border-gray-600 {
border-color: #444444 !important;
}
.dark .border-gray-300 {
border-color: #333333 !important;
}
.dark .border-gray-200 {
border-color: #2a2a2a !important;
}
.dark .border-gray-100 {
border-color: #2a2a2a !important;
}
/* 文字色 - 纯白灰 */
.dark .text-gray-900 {
color: #f5f5f5 !important;
}
.dark .text-gray-700 {
color: #e0e0e0 !important;
}
.dark .text-gray-600 {
color: #b0b0b0 !important;
}
.dark .text-gray-500 {
color: #909090 !important;
}
.dark .text-gray-400 {
color: #707070 !important;
}
.dark .text-gray-300 {
color: #d0d0d0 !important;
}
.dark .text-white {
color: #ffffff !important;
}
.dark .text-gray-800 {
color: #e0e0e0 !important;
}
.dark .text-gray-200 {
color: #d0d0d0 !important;
}
.dark .text-gray-100 {
color: #e0e0e0 !important;
}
/* 透明度覆盖 */
.dark .bg-opacity-0 {
--tw-bg-opacity: 0 !important;
}
.dark .bg-opacity-10 {
--tw-bg-opacity: 0.1 !important;
}
.dark .bg-opacity-20 {
--tw-bg-opacity: 0.2 !important;
}
.dark .bg-opacity-30 {
--tw-bg-opacity: 0.3 !important;
}
.dark .bg-opacity-50 {
--tw-bg-opacity: 0.5 !important;
}
/* 悬停效果 - 深灰 */
.dark .hover\:bg-gray-100:hover {
background-color: #2a2a2a !important;
}
.dark .hover\:bg-gray-700:hover {
background-color: #333333 !important;
}
.dark .hover\:bg-gray-600:hover {
background-color: #3a3a3a !important;
}
.dark .hover\:bg-gray-200:hover {
background-color: #2a2a2a !important;
}
.dark .hover\:bg-gray-50:hover {
background-color: #2a2a2a !important;
}
/* 黑色相关 - 但不影响透明遮罩 */
.dark .bg-black:not(.bg-opacity-0):not(.bg-opacity-10):not(.bg-opacity-20):not(.bg-opacity-30) {
background-color: #0a0a0a !important;
}
.dark .text-black {
color: #ffffff !important;
}
.dark .border-black {
border-color: #2a2a2a !important;
}
/* 移除所有颜色调,统一为黑灰 */
/* 蓝色系 -> 黑灰 */
.dark .bg-blue-50 {
background-color: #2a2a2a !important;
}
.dark .bg-blue-100 {
background-color: #2a2a2a !important;
}
.dark .bg-blue-200 {
background-color: #3a3a3a !important;
}
.dark .bg-blue-500 {
background-color: #4a4a4a !important;
}
.dark .bg-blue-600 {
background-color: #3a3a3a !important;
}
.dark .bg-blue-800 {
background-color: #2a2a2a !important;
}
.dark .bg-blue-900 {
background-color: #1a1a1a !important;
}
.dark .text-blue-300 {
color: #d0d0d0 !important;
}
.dark .text-blue-400 {
color: #e0e0e0 !important;
}
.dark .text-blue-500 {
color: #f0f0f0 !important;
}
.dark .text-blue-600 {
color: #f0f0f0 !important;
}
.dark .text-blue-700 {
color: #e0e0e0 !important;
}
.dark .border-blue-200 {
border-color: #2a2a2a !important;
}
.dark .border-blue-500 {
border-color: #4a4a4a !important;
}
.dark .border-blue-700 {
border-color: #333333 !important;
}
.dark .hover\:bg-blue-600:hover {
background-color: #4a4a4a !important;
}
.dark .hover\:bg-blue-50:hover {
background-color: #333333 !important;
}
/* 绿色系 -> 黑灰 */
.dark .bg-green-50 {
background-color: #2a2a2a !important;
}
.dark .text-green-600 {
color: #e0e0e0 !important;
}
/* 红色系 -> 黑灰 */
.dark .bg-red-50 {
background-color: #2a2a2a !important;
}
.dark .text-red-600 {
color: #f0a0a0 !important;
}
/* 黄色系 -> 黑灰 */
.dark .bg-yellow-50 {
background-color: #2a2a2a !important;
}
.dark .text-yellow-600 {
color: #e0e0a0 !important;
}
/* 图片容器不要覆盖 */
.dark img {
background-color: transparent !important;
}
/* 输入框和选择框 */
.dark input,
.dark select,
.dark textarea {
background-color: #1a1a1a !important;
border-color: #333333 !important;
color: #e0e0e0 !important;
}
.dark input:focus,
.dark select:focus,
.dark textarea:focus {
border-color: #4a4a4a !important;
outline: none !important;
--tw-ring-color: #4a4a4a !important;
}
.dark input::placeholder {
color: #707070 !important;
}
/* 按钮 */
.dark button {
color: #e0e0e0 !important;
}
.dark .bg-blue-500 {
background-color: #4a4a4a !important;
}
.dark .hover\:bg-blue-600:hover {
background-color: #5a5a5a !important;
}
/* 阴影 */
.dark .shadow-lg {
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.5), 0 4px 6px -2px rgba(0, 0, 0, 0.3) !important;
}
.dark .shadow-xl {
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.5), 0 10px 10px -5px rgba(0, 0, 0, 0.3) !important;
}
.dark .hover\:shadow-lg:hover {
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.5), 0 4px 6px -2px rgba(0, 0, 0, 0.3) !important;
}
/* Ring (focus outline) */
.dark .ring-blue-500 {
--tw-ring-color: #4a4a4a !important;
}
.dark .focus\:ring-blue-500:focus {
--tw-ring-color: #4a4a4a !important;
}
.dark .focus\:ring-2:focus {
--tw-ring-offset-shadow: 0 0 0 0px #000 !important;
--tw-ring-shadow: 0 0 0 2px #4a4a4a !important;
}
/* Custom scrollbar */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: transparent;
}
/* 亮色主题滚动条 */
::-webkit-scrollbar-thumb {
background: rgba(0, 0, 0, 0.2);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(0, 0, 0, 0.3);
}
/* 暗色主题滚动条 */
.dark ::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.05);
}
.dark ::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.2);
border-radius: 4px;
}
.dark ::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.3);
}
+10
View File
@@ -0,0 +1,10 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
+48
View File
@@ -0,0 +1,48 @@
import axios from 'axios';
const API_BASE = '/api';
// Library API
export const libraryAPI = {
getAll: () => axios.get(`${API_BASE}/library`),
add: (name, path) => axios.post(`${API_BASE}/library`, { name, path }),
update: (id, updates) => axios.put(`${API_BASE}/library/${id}`, updates),
delete: (id) => axios.delete(`${API_BASE}/library/${id}`),
setCurrent: (id) => axios.post(`${API_BASE}/library/${id}/set-current`),
updatePreferences: (preferences) => axios.put(`${API_BASE}/library/preferences`, preferences),
updateTheme: (theme) => axios.put(`${API_BASE}/library/theme`, { theme })
};
// Image API
export const imageAPI = {
search: (libraryId, params = {}) => {
const query = new URLSearchParams({
libraryId,
...params
});
return axios.get(`${API_BASE}/image?${query}`);
},
getCount: (libraryId) => axios.get(`${API_BASE}/image/count?libraryId=${libraryId}`),
getFolders: (libraryId) => axios.get(`${API_BASE}/image/folders?libraryId=${libraryId}`),
getThumbnailUrl: (libraryId, size, filename) => `${API_BASE}/image/thumbnail/${libraryId}/${size}/${filename}`,
getOriginalUrl: (libraryId, path) => `${API_BASE}/image/original/${libraryId}/${path}`,
openInExplorer: (libraryId, path) => axios.post(`${API_BASE}/image/${libraryId}/open-file`, { path })
};
// Scan API
export const scanAPI = {
fullScan: (libraryId, wait = false) => axios.post(`${API_BASE}/scan/full`, { libraryId, wait }),
sync: (libraryId, wait = false) => axios.post(`${API_BASE}/scan/sync`, { libraryId, wait }),
stop: (libraryId) => axios.post(`${API_BASE}/scan/stop`, { libraryId }),
resume: (libraryId) => axios.post(`${API_BASE}/scan/resume`, { libraryId }),
getStatus: (libraryId) => axios.get(`${API_BASE}/scan/status/${libraryId}`),
fixFolders: (libraryId) => axios.post(`${API_BASE}/scan/fix-folders`, { libraryId })
};
// Watch API
export const watchAPI = {
start: (libraryId) => axios.post(`${API_BASE}/watch/start/${libraryId}`),
stop: (libraryId) => axios.post(`${API_BASE}/watch/stop/${libraryId}`),
status: (libraryId) => axios.get(`${API_BASE}/watch/status/${libraryId}`),
list: () => axios.get(`${API_BASE}/watch/list`)
};
+111
View File
@@ -0,0 +1,111 @@
import { create } from 'zustand';
const useStore = create((set, get) => ({
// Theme
theme: 'light',
setTheme: (theme) => set({ theme }),
toggleTheme: () => set((state) => ({ theme: state.theme === 'light' ? 'dark' : 'light' })),
// Libraries
libraries: [],
currentLibraryId: null,
setLibraries: (libraries) => set({ libraries }),
setCurrentLibrary: (id) => set({ currentLibraryId: id }),
addLibrary: (library) => set((state) => ({ libraries: [...state.libraries, library] })),
removeLibrary: (id) => set((state) => ({
libraries: state.libraries.filter((lib) => lib.id !== id),
currentLibraryId: state.currentLibraryId === id ? null : state.currentLibraryId
})),
// Images
images: [],
filteredImages: [],
totalImageCount: 0, // 整个素材库的总图片数
setImages: (images) => set({ images, filteredImages: images }),
setFilteredImages: (filteredImages) => set({ filteredImages }),
setTotalImageCount: (count) => set({ totalImageCount: count }),
// Folders
folders: [],
selectedFolder: null,
setFolders: (folders) => set({ folders }),
setSelectedFolder: (folder) => set({ selectedFolder: folder }),
// Search and filters
searchKeywords: '',
filters: {
formats: [],
minSize: null,
maxSize: null,
startDate: null,
endDate: null
},
setSearchKeywords: (keywords) => set({ searchKeywords: keywords }),
setFilters: (filters) => set((state) => ({ filters: { ...state.filters, ...filters } })),
resetFilters: () => set({
searchKeywords: '',
filters: {
formats: [],
minSize: null,
maxSize: null,
startDate: null,
endDate: null
}
}),
// Selected image (单选)
selectedImage: null,
setSelectedImage: (image) => set({ selectedImage: image }),
// Selected images (多选)
selectedImages: [],
setSelectedImages: (images) => set({ selectedImages: images }),
toggleImageSelection: (image) => set((state) => {
const isSelected = state.selectedImages.some(img => img.path === image.path);
if (isSelected) {
return { selectedImages: state.selectedImages.filter(img => img.path !== image.path) };
} else {
return { selectedImages: [...state.selectedImages, image] };
}
}),
clearSelection: () => set({ selectedImages: [], selectedImage: null }),
// Scan progress
scanProgress: null,
scanStartTime: null, // 扫描开始时间
setScanProgress: (progress) => set((state) => {
// 第一次收到进度时记录开始时间
if (progress && !state.scanStartTime && progress.current > 0) {
return { scanProgress: progress, scanStartTime: Date.now() };
}
// 扫描结束时清空开始时间
if (!progress) {
return { scanProgress: null, scanStartTime: null };
}
return { scanProgress: progress };
}),
// Panel resizing state(拖动侧边栏时置为 true,用于抑制重算)
isResizingPanels: false,
setIsResizingPanels: (value) => set({ isResizingPanels: value }),
// 正在拖动的侧边:'left' | 'right' | null
resizingSide: null,
setResizingSide: (side) => set({ resizingSide: side }),
// Thumbnail size
thumbnailHeight: 200,
setThumbnailHeight: (height) => set({ thumbnailHeight: height }),
// Mobile view state
mobileView: 'main', // 'sidebar' | 'main' | 'detail'
setMobileView: (view) => set({ mobileView: view }),
// Get current library
getCurrentLibrary: () => {
const state = get();
return state.libraries.find((lib) => lib.id === state.currentLibraryId);
}
}));
export default useStore;
+104
View File
@@ -0,0 +1,104 @@
/**
* 瀑布流布局计算 Worker
* 将耗时的布局计算移到后台线程,避免阻塞主线程
*/
/**
* 计算瀑布流布局
* @param {Array} images - 图片列表
* @param {number} containerWidth - 容器宽度
* @param {number} targetHeight - 目标行高
* @returns {Array} 计算后的行数组
*/
function calculateLayout(images, containerWidth, targetHeight) {
if (!images.length || !containerWidth) {
return [];
}
const gap = 16;
const calculatedRows = [];
let currentRow = [];
let currentRowWidthSum = 0;
images.forEach((image, index) => {
const aspectRatio = image.width / image.height;
const imageWidth = targetHeight * aspectRatio;
// Add to current row
currentRow.push({
...image,
originalWidth: imageWidth,
aspectRatio: aspectRatio
});
currentRowWidthSum += imageWidth;
// Calculate if current row is ready to be finalized
const currentGaps = (currentRow.length - 1) * gap;
const totalWidth = currentRowWidthSum + currentGaps;
const isLastImage = index === images.length - 1;
// Decide if we should finish this row
let shouldFinishRow = false;
if (isLastImage) {
shouldFinishRow = true;
} else if (totalWidth >= containerWidth * 0.95) {
shouldFinishRow = true;
} else {
const nextImage = images[index + 1];
if (nextImage) {
const nextAspectRatio = nextImage.width / nextImage.height;
const nextImageWidth = targetHeight * nextAspectRatio;
const nextTotalWidth = currentRowWidthSum + nextImageWidth + (currentRow.length * gap);
if (nextTotalWidth > containerWidth * 1.2) {
shouldFinishRow = true;
}
}
}
if (shouldFinishRow) {
const totalGaps = (currentRow.length - 1) * gap;
const availableWidth = containerWidth - totalGaps;
let scale = availableWidth / currentRowWidthSum;
if (isLastImage && currentRow.length < 3) {
scale = Math.min(scale, 1.2);
}
const rowHeight = targetHeight * scale;
currentRow = currentRow.map(img => ({
...img,
calculatedWidth: img.originalWidth * scale,
calculatedHeight: rowHeight
}));
calculatedRows.push(currentRow);
currentRow = [];
currentRowWidthSum = 0;
}
});
return calculatedRows;
}
// 监听主线程消息
self.onmessage = function(e) {
const { images, containerWidth, targetHeight, requestId } = e.data;
const startTime = performance.now();
const rows = calculateLayout(images, containerWidth, targetHeight);
const duration = performance.now() - startTime;
// 返回结果
self.postMessage({
rows,
requestId,
duration,
imageCount: images.length,
rowCount: rows.length
});
};