diff --git a/backend/server.js b/backend/server.js
index 8e6e1cd..f9034de 100644
--- a/backend/server.js
+++ b/backend/server.js
@@ -173,11 +173,24 @@ server.listen(PORT, () => {
}
}
- // 为当前素材库启动文件监控
+ // 为当前素材库启动文件监控(仅当索引存在时)
if (currentConfig.currentLibraryId) {
const currentLib = currentConfig.libraries.find(lib => lib.id === currentConfig.currentLibraryId);
if (currentLib) {
- lightweightWatcher.watch(currentLib.id, currentLib.path, currentLib.name, io);
+ const fs = require('fs');
+ const { getFlypicPath, getDatabasePath } = require('./src/config');
+ const flypicPath = getFlypicPath(currentLib.path);
+ const dbPath = getDatabasePath(currentLib.path);
+
+ // 只有当文件夹和索引都存在时才启动监控
+ const folderExists = fs.existsSync(currentLib.path);
+ const indexExists = fs.existsSync(flypicPath) && fs.existsSync(dbPath);
+
+ if (folderExists && indexExists) {
+ lightweightWatcher.watch(currentLib.id, currentLib.path, currentLib.name, io);
+ } else {
+ console.log(`⚠️ 跳过文件监控: ${currentLib.name} (${!folderExists ? '文件夹不存在' : '索引不存在'})`);
+ }
}
}
} catch (e) {
diff --git a/backend/src/routes/library.js b/backend/src/routes/library.js
index 6919901..0faaae0 100644
--- a/backend/src/routes/library.js
+++ b/backend/src/routes/library.js
@@ -79,10 +79,12 @@ router.put('/:id', asyncHandler(async (req, res) => {
/**
* 删除素材库
* DELETE /api/library/:id
+ * Query: autoSelectNext - 是否自动选择下一个素材库,默认 true
*/
router.delete('/:id', asyncHandler(async (req, res) => {
const { id } = req.params;
- const result = await libraryService.deleteLibrary(id);
+ const autoSelectNext = req.query.autoSelectNext !== 'false';
+ const result = await libraryService.deleteLibrary(id, autoSelectNext);
res.json({ success: true, data: result });
}));
@@ -106,4 +108,14 @@ router.get('/:id/stats', asyncHandler(async (req, res) => {
res.json({ success: true, data: result });
}));
+/**
+ * 验证素材库路径是否存在
+ * GET /api/library/:id/validate
+ */
+router.get('/:id/validate', asyncHandler(async (req, res) => {
+ const { id } = req.params;
+ const result = libraryService.validateLibraryPath(id);
+ res.json({ success: true, data: result });
+}));
+
module.exports = router;
diff --git a/backend/src/services/LibraryService.js b/backend/src/services/LibraryService.js
index 06097f2..dfc8bfa 100644
--- a/backend/src/services/LibraryService.js
+++ b/backend/src/services/LibraryService.js
@@ -6,7 +6,7 @@
const fs = require('fs');
const path = require('path');
const { NotFoundError, ValidationError } = require('../middleware/errorHandler');
-const { getFlypicPath, getDatabasePath } = require('../config');
+const { getFlypicPath, getDatabasePath, getThumbnailsPath } = require('../config');
class LibraryService {
constructor(configManager, dbPool, scanManager, lightweightWatcher, io) {
@@ -126,8 +126,10 @@ class LibraryService {
/**
* 删除素材库
+ * @param {string} id - 素材库ID
+ * @param {boolean} autoSelectNext - 是否自动选择下一个素材库,默认 true
*/
- async deleteLibrary(id) {
+ async deleteLibrary(id, autoSelectNext = true) {
const config = this.configManager.load();
const library = config.libraries.find(lib => lib.id === id);
@@ -139,7 +141,7 @@ class LibraryService {
await this._cleanupLibraryResources(id, library.path);
// 删除配置
- this.configManager.removeLibrary(id);
+ this.configManager.removeLibrary(id, autoSelectNext);
return {
success: true,
@@ -239,6 +241,43 @@ class LibraryService {
await new Promise(resolve => setTimeout(resolve, 300));
}
+ /**
+ * 验证素材库路径是否存在
+ * 返回三种状态:
+ * - status: 'ok' - 素材库正常(文件夹和索引都存在)
+ * - status: 'missing_index' - 文件夹存在但索引不存在(需要重新扫描)
+ * - status: 'missing_folder' - 文件夹不存在(需要打开其他或新建)
+ */
+ validateLibraryPath(libraryId) {
+ const config = this.configManager.load();
+ const library = config.libraries.find(lib => lib.id === libraryId);
+
+ if (!library) {
+ throw new NotFoundError('Library', libraryId);
+ }
+
+ const folderExists = fs.existsSync(library.path);
+ const flypicPath = getFlypicPath(library.path);
+ const dbPath = getDatabasePath(library.path);
+ const indexExists = fs.existsSync(flypicPath) && fs.existsSync(dbPath);
+
+ let status = 'ok';
+ if (!folderExists) {
+ status = 'missing_folder';
+ } else if (!indexExists) {
+ status = 'missing_index';
+ }
+
+ return {
+ libraryId,
+ path: library.path,
+ name: library.name,
+ folderExists,
+ indexExists,
+ status
+ };
+ }
+
/**
* 获取素材库统计信息
*/
diff --git a/backend/utils/config.js b/backend/utils/config.js
index e4fa34c..1aeff6b 100644
--- a/backend/utils/config.js
+++ b/backend/utils/config.js
@@ -149,13 +149,19 @@ function addLibrary(name, libraryPath) {
/**
* Remove library from config
+ * @param {string} libraryId - 要删除的素材库ID
+ * @param {boolean} autoSelectNext - 是否自动选择下一个素材库,默认 true
*/
-function removeLibrary(libraryId) {
+function removeLibrary(libraryId, autoSelectNext = true) {
const config = loadConfig();
config.libraries = config.libraries.filter(lib => lib.id !== libraryId);
if (config.currentLibraryId === libraryId) {
- config.currentLibraryId = config.libraries.length > 0 ? config.libraries[0].id : null;
+ if (autoSelectNext) {
+ config.currentLibraryId = config.libraries.length > 0 ? config.libraries[0].id : null;
+ } else {
+ config.currentLibraryId = null;
+ }
}
saveConfig(config);
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 4bb2b04..bf8ffc7 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -10,10 +10,17 @@ import Sidebar from './components/Sidebar';
import MainContent from './components/MainContent';
import RightPanel from './components/RightPanel';
import Header from './components/Header';
+import LibraryMissingModal from './components/LibraryMissingModal';
function App() {
const { theme, mobileView, setMobileView } = useUIStore();
- const { setLibraries, setCurrentLibrary } = useLibraryStore();
+ const {
+ setLibraries,
+ setCurrentLibrary,
+ removeLibrary,
+ setShowAddLibraryForm,
+ triggerExpandLibrarySelector
+ } = useLibraryStore();
const { selectedImage } = useImageStore();
const { setScanProgress } = useScanStore();
const [leftWidth, setLeftWidth] = useState(256); // 默认 256px (w-64)
@@ -23,6 +30,7 @@ function App() {
const [isMobile, setIsMobile] = useState(false);
const [isConnecting, setIsConnecting] = useState(true); // 启动加载状态
const [connectionError, setConnectionError] = useState(null);
+ const [missingLibrary, setMissingLibrary] = useState(null); // 丢失的素材库信息
const containerRef = useRef(null);
useEffect(() => {
@@ -202,6 +210,28 @@ function App() {
}
if (libId) {
+ // 验证当前素材库路径是否存在
+ try {
+ const validateRes = await libraryAPI.validate(libId);
+ const validateData = validateRes.data || validateRes;
+
+ // 检查状态:ok / missing_index / missing_folder
+ if (validateData.status !== 'ok') {
+ // 路径或索引不存在,显示弹窗
+ setMissingLibrary({
+ id: libId,
+ name: validateData.name,
+ path: validateData.path,
+ status: validateData.status // 'missing_index' 或 'missing_folder'
+ });
+ setIsConnecting(false);
+ return; // 不继续加载
+ }
+ } catch (validateError) {
+ console.warn('验证素材库路径失败:', validateError.message);
+ // 验证失败时继续正常加载
+ }
+
// 加载文件夹和统计信息(包含 totalSize)
await loadFolders(libId);
@@ -397,11 +427,85 @@ function App() {
);
}
+ // 素材库路径丢失弹窗处理函数
+ const handleRescanLibrary = async () => {
+ if (!missingLibrary) return;
+
+ // 关闭弹窗
+ setMissingLibrary(null);
+
+ // 触发全量扫描
+ try {
+ await scanAPI.fullScan(missingLibrary.id);
+ // 扫描会通过 Socket.IO 推送进度
+ } catch (error) {
+ console.error('启动扫描失败:', error.message);
+ alert('启动扫描失败: ' + error.message);
+ }
+ };
+
+ const handleOpenOtherLibrary = async () => {
+ if (!missingLibrary) return;
+
+ // 从配置中移除当前素材库(不自动选择下一个)
+ try {
+ await libraryAPI.remove(missingLibrary.id, false);
+ removeLibrary(missingLibrary.id);
+
+ // 清空当前素材库,让用户自己选择
+ setCurrentLibrary(null);
+ useImageStore.getState().setImages([]);
+ useImageStore.getState().setFolders([]);
+ useImageStore.getState().setTotalImageCount(0);
+ useImageStore.getState().setSelectedFolder(null);
+ } catch (error) {
+ console.error('移除素材库失败:', error.message);
+ }
+
+ // 关闭弹窗
+ setMissingLibrary(null);
+
+ // 触发展开素材库选择器
+ setTimeout(() => {
+ triggerExpandLibrarySelector();
+ }, 100);
+ };
+
+ const handleCreateNewLibrary = async () => {
+ if (!missingLibrary) return;
+
+ // 从配置中移除当前素材库
+ try {
+ await libraryAPI.remove(missingLibrary.id);
+ removeLibrary(missingLibrary.id);
+ } catch (error) {
+ console.error('移除素材库失败:', error.message);
+ }
+
+ // 关闭弹窗
+ setMissingLibrary(null);
+
+ // 触发显示新建素材库表单
+ setTimeout(() => {
+ setShowAddLibraryForm(true);
+ }, 100);
+ };
+
// 移动端布局
if (isMobile) {
return (
+ {/* 素材库路径丢失弹窗 */}
+
{/* 侧边栏视图 */}
+ {/* 素材库路径丢失弹窗 */}
+
{/* 左侧边栏 */}
diff --git a/frontend/src/api/endpoints/library.js b/frontend/src/api/endpoints/library.js
index 4c27ddc..8910b08 100644
--- a/frontend/src/api/endpoints/library.js
+++ b/frontend/src/api/endpoints/library.js
@@ -27,9 +27,11 @@ export async function update(id, updates) {
/**
* 删除素材库
+ * @param {string} id - 素材库ID
+ * @param {boolean} autoSelectNext - 是否自动选择下一个素材库,默认 true
*/
-export async function remove(id) {
- return api.delete(`/library/${id}`);
+export async function remove(id, autoSelectNext = true) {
+ return api.delete(`/library/${id}?autoSelectNext=${autoSelectNext}`);
}
/**
@@ -57,3 +59,10 @@ export async function updatePreferences(preferences) {
export async function updateTheme(theme) {
return api.put('/library/theme', { theme });
}
+
+/**
+ * 验证素材库路径是否存在
+ */
+export async function validate(id) {
+ return api.get(`/library/${id}/validate`);
+}
diff --git a/frontend/src/components/Dashboard.jsx b/frontend/src/components/Dashboard.jsx
index ad9be71..7026fb2 100644
--- a/frontend/src/components/Dashboard.jsx
+++ b/frontend/src/components/Dashboard.jsx
@@ -31,9 +31,11 @@ function Dashboard() {
{currentLibrary?.name || '素材库'}
-
- {currentLibrary?.path}
-
+ {currentLibrary?.path && (
+
+ {currentLibrary.path}
+
+ )}
{/* Stats Cards */}
diff --git a/frontend/src/components/LibraryMissingModal.jsx b/frontend/src/components/LibraryMissingModal.jsx
new file mode 100644
index 0000000..2c788b4
--- /dev/null
+++ b/frontend/src/components/LibraryMissingModal.jsx
@@ -0,0 +1,159 @@
+import { AlertTriangle, FolderOpen, Plus, RefreshCw } from 'lucide-react';
+
+/**
+ * 素材库路径丢失弹窗
+ * 两种状态:
+ * - missing_index: 文件夹存在但索引不存在(可重新扫描)
+ * - missing_folder: 文件夹不存在(只能打开其他或新建)
+ */
+function LibraryMissingModal({
+ isOpen,
+ libraryName,
+ libraryPath,
+ status, // 'missing_index' | 'missing_folder'
+ onRescan,
+ onOpenOther,
+ onCreateNew
+}) {
+ if (!isOpen) return null;
+
+ const isMissingIndex = status === 'missing_index';
+ const title = isMissingIndex ? '素材库索引丢失' : '打开资源库失败';
+
+ return (
+
+
+
+ {/* 左侧内容 */}
+
+ {/* 标题 */}
+
+
+ {/* 描述 */}
+
+ {isMissingIndex ? (
+ <>
+
+ 素材库 {libraryName} 的索引数据已丢失。
+
+
+ 路径: {libraryPath}
+
+
+ 图片文件夹仍然存在,您可以重新扫描来重建索引。
+
+ >
+ ) : (
+ <>
+
+ 在这个位置的资源库(
+ {libraryPath}
+ ) 打开失败,可能是因为路径已经变化,或者资源库链接错误。
+
+
+ 如果您更改过资源库位置,可以{' '}
+
+ {' '}打开
+
+ >
+ )}
+
+
+ {/* 分隔线 */}
+
+ {isMissingIndex ? '请选择操作:' : '您也可以:'}
+
+
+ {/* 操作按钮 */}
+
+ {isMissingIndex && (
+
+ )}
+
+
+
+
+
+ {/* 右侧插图 */}
+
+
+ {/* 简化的插图:房子和警告标志 */}
+
+
+
+
+
+
+
+ );
+}
+
+export default LibraryMissingModal;
diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx
index 7ed2ab9..9796b4a 100644
--- a/frontend/src/components/Sidebar.jsx
+++ b/frontend/src/components/Sidebar.jsx
@@ -6,6 +6,7 @@ import { useScanStore } from '../stores/useScanStore';
import { libraryAPI, scanAPI, imageAPI } from '../api';
import requestManager from '../services/requestManager';
import { onUserActionStart } from '../services/imageLoadService';
+import LibraryMissingModal from './LibraryMissingModal';
// 检查素材库扫描状态
const checkScanStatus = async (libraryId) => {
@@ -18,7 +19,17 @@ const checkScanStatus = async (libraryId) => {
};
function Sidebar() {
- const { libraries, currentLibraryId, setCurrentLibrary, addLibrary, removeLibrary } = useLibraryStore();
+ const {
+ libraries,
+ currentLibraryId,
+ setCurrentLibrary,
+ addLibrary,
+ removeLibrary,
+ showAddLibraryForm,
+ setShowAddLibraryForm,
+ expandLibrarySelector,
+ resetExpandLibrarySelector
+ } = useLibraryStore();
const { folders, selectedFolder, totalImageCount, setSelectedFolder } = useImageStore();
const { isScanning } = useScanStore();
@@ -30,7 +41,10 @@ function Sidebar() {
const [expandedFolders, setExpandedFolders] = useState(new Set());
const [isAdding, setIsAdding] = useState(false);
const [isSwitching, setIsSwitching] = useState(false);
+ const [missingLibrary, setMissingLibrary] = useState(null); // 切换时发现的丢失素材库
+ const [isLibrarySelectorOpen, setIsLibrarySelectorOpen] = useState(false); // 素材库选择器展开状态
const folderSearchDebounceRef = useRef(null);
+ const librarySelectorRef = useRef(null);
// 文件夹搜索防抖(300ms)
const handleFolderSearchChange = (value) => {
@@ -54,6 +68,36 @@ function Sidebar() {
};
}, []);
+ // 响应全局状态:显示新建素材库表单
+ useEffect(() => {
+ if (showAddLibraryForm) {
+ setShowAddLibrary(true);
+ setShowAddLibraryForm(false); // 重置全局状态
+ }
+ }, [showAddLibraryForm, setShowAddLibraryForm]);
+
+ // 响应全局状态:展开素材库选择器
+ useEffect(() => {
+ if (expandLibrarySelector) {
+ setIsLibrarySelectorOpen(true);
+ resetExpandLibrarySelector(); // 重置全局状态
+ }
+ }, [expandLibrarySelector, resetExpandLibrarySelector]);
+
+ // 点击外部关闭下拉菜单
+ useEffect(() => {
+ const handleClickOutside = (event) => {
+ if (librarySelectorRef.current && !librarySelectorRef.current.contains(event.target)) {
+ setIsLibrarySelectorOpen(false);
+ }
+ };
+
+ if (isLibrarySelectorOpen) {
+ document.addEventListener('mousedown', handleClickOutside);
+ return () => document.removeEventListener('mousedown', handleClickOutside);
+ }
+ }, [isLibrarySelectorOpen]);
+
const handleAddLibrary = async () => {
// 扫描期间禁止添加素材库
if (isScanning()) {
@@ -183,6 +227,22 @@ function Sidebar() {
setIsSwitching(true);
try {
+ // 0. 先验证目标素材库路径是否存在
+ const validateRes = await libraryAPI.validate(libraryId);
+ const validateData = validateRes.data || validateRes;
+
+ if (validateData.status !== 'ok') {
+ // 路径或索引不存在,显示弹窗
+ setMissingLibrary({
+ id: libraryId,
+ name: validateData.name,
+ path: validateData.path,
+ status: validateData.status
+ });
+ setIsSwitching(false);
+ return;
+ }
+
// 1. 暂停空闲加载并取消所有之前的请求
onUserActionStart();
requestManager.cancelAllRequests();
@@ -459,8 +519,88 @@ function Sidebar() {
});
};
+ // 弹窗处理函数
+ const handleMissingRescan = async () => {
+ if (!missingLibrary) return;
+ const libId = missingLibrary.id;
+ setMissingLibrary(null);
+
+ try {
+ // 1. 清理当前状态
+ useScanStore.getState().setScanProgress(null);
+ useImageStore.getState().setSelectedImage(null);
+ useImageStore.getState().setImages([]);
+ useImageStore.getState().setFolders([]);
+ useImageStore.getState().setTotalImageCount(0);
+ setSelectedFolder(null);
+
+ // 2. 先切换到该素材库(后端)
+ await libraryAPI.setCurrent(libId);
+
+ // 3. 更新前端状态(这会触发 UI 更新,select 会显示正确的值)
+ setCurrentLibrary(libId);
+
+ // 4. 启动扫描(扫描进度会通过 Socket.IO 推送)
+ await scanAPI.fullScan(libId);
+ } catch (error) {
+ console.error('启动扫描失败:', error.message);
+ alert('启动扫描失败: ' + error.message);
+ }
+ };
+
+ const handleMissingOpenOther = async () => {
+ if (!missingLibrary) return;
+
+ try {
+ // 删除时不自动选择下一个素材库
+ await libraryAPI.remove(missingLibrary.id, false);
+ removeLibrary(missingLibrary.id);
+
+ // 清空当前素材库,让用户自己选择
+ setCurrentLibrary(null);
+ useImageStore.getState().setImages([]);
+ useImageStore.getState().setFolders([]);
+ useImageStore.getState().setTotalImageCount(0);
+ setSelectedFolder(null);
+ } catch (error) {
+ console.error('移除素材库失败:', error.message);
+ }
+
+ setMissingLibrary(null);
+
+ // 展开素材库选择器让用户选择
+ setTimeout(() => {
+ setIsLibrarySelectorOpen(true);
+ }, 100);
+ };
+
+ const handleMissingCreateNew = async () => {
+ if (!missingLibrary) return;
+
+ try {
+ await libraryAPI.remove(missingLibrary.id);
+ removeLibrary(missingLibrary.id);
+ } catch (error) {
+ console.error('移除素材库失败:', error.message);
+ }
+
+ setMissingLibrary(null);
+ setShowAddLibrary(true);
+ };
+
return (
+ {/* 素材库路径丢失弹窗 */}
+
+
{/* Library Management */}
@@ -469,38 +609,65 @@ function Sidebar() {
{/* Library Selector with Delete Button */}
-
-