diff --git a/.kiro/specs/library-switch-optimization/design.md b/.kiro/specs/library-switch-optimization/design.md index 5bfa74b..5aff458 100644 --- a/.kiro/specs/library-switch-optimization/design.md +++ b/.kiro/specs/library-switch-optimization/design.md @@ -93,41 +93,23 @@ interface RequestContext { } ``` -### 2. ImageLoadService (新增) +### 2. ImageLoadService (工具函数集合) -负责图片的分批加载和空闲加载逻辑。 +提供空闲加载控制的工具函数,状态由 Store 统一管理。 ```typescript -interface ImageLoadService { - // 加载文件夹的第一批图片 - loadInitialBatch(libraryId: string, folder: string | null): Promise; - - // 加载下一批图片 - loadNextBatch(): Promise; - - // 开始空闲加载 - startIdleLoading(): void; - - // 暂停空闲加载 - pauseIdleLoading(): void; - - // 获取加载状态 - getLoadingState(): LoadingState; -} +// 用户操作开始时调用,暂停空闲加载并取消请求 +function onUserActionStart(): void; -interface ImageBatch { - images: Image[]; - offset: number; - total: number; - hasMore: boolean; -} +// 用户操作结束时调用,恢复空闲加载 +function onUserActionEnd(hasMore: boolean): void; -interface LoadingState { - isLoading: boolean; - loadedCount: number; - totalCount: number; - currentFolder: string | null; -} +// 暂停/恢复空闲加载 +function pauseIdleLoading(): void; +function resumeIdleLoading(): void; + +// 检查空闲加载是否暂停 +function isIdlePaused(): boolean; ``` ### 3. 后端 API 扩展 @@ -156,93 +138,28 @@ interface ImageSearchResponse { ```typescript // useStore 新增状态 interface ImageLoadingState { - // 当前加载状态 - isLoadingImages: boolean; - loadedImageCount: number; - totalImageCount: number; - hasMoreImages: boolean; - - // 当前加载上下文 - currentLoadContext: { - libraryId: string | null; - folder: string | null; - requestId: string | null; - }; + isLoading: boolean; // 是否正在加载 + loadedCount: number; // 已加载数量 + totalCount: number; // 总数量 + hasMore: boolean; // 是否还有更多 } ``` -### 5. CacheService (新增) + ## Data Models @@ -258,94 +175,7 @@ interface RequestContext { } ``` -### 加载队列项 - -```typescript -interface LoadQueueItem { - libraryId: string; - folder: string | null; - offset: number; - limit: number; - priority: 'high' | 'normal' | 'idle'; - requestContext: RequestContext; -} -``` - -### 缓存文件结构 - -缓存文件存储在 `.flypic/cache/` 目录下: - -``` -.flypic/ -├── metadata.db # SQLite 数据库 -├── thumbnails/ # 缩略图 -└── cache/ # 新增:缓存目录 - ├── library.json # 素材库级别缓存(文件夹树+元数据) - └── folders/ # 文件夹级别缓存 - ├── {hash1}.json # 文件夹图片列表缓存 - └── {hash2}.json -``` - -### 缓存文件格式 - -```typescript -// library.json -interface LibraryCacheFile { - version: 1; - libraryId: string; - createdAt: number; - dbModifiedAt: number; - totalCount: number; - folderTree: FolderNode[]; -} - -// folders/{hash}.json -interface FolderCacheFile { - version: 1; - folder: string; - cachedAt: number; - folderModifiedAt: number; // 该文件夹最后修改时间 - images: ImageMetadata[]; // 精简的图片元数据 -} - -// 精简的图片元数据(减少缓存大小) -interface ImageMetadata { - id: number; - path: string; - filename: string; - width: number; - height: number; - thumbnail_path: string; - file_type: string; - created_at: number; -} -``` - -## 缓存策略 - -### 缓存失效判断 - -```mermaid -flowchart TD - A[切换素材库] --> B{缓存文件存在?} - B -->|否| C[从数据库加载] - B -->|是| D[读取缓存] - D --> E{获取DB修改时间} - E --> F{缓存时间 >= DB修改时间?} - F -->|是| G[使用缓存数据] - F -->|否| H[缓存失效,重新加载] - G --> I[后台校验增量变化] - H --> C - C --> J[保存到缓存] -``` - -### 增量更新 - -当检测到数据库有变化时,不需要完全重建缓存: - -1. 比较 `indexed_at` 时间戳找出新增/修改的图片 -2. 比较文件夹列表找出新增/删除的文件夹 -3. 只更新变化的部分 + @@ -397,33 +227,7 @@ flowchart TD *For any* batch load completion, the displayed image count should increase by the batch size (or remaining count if less). **Validates: Requirements 5.2** -### Property 12: Cache file creation after full load -*For any* library that completes full image loading, a cache file should exist in the .flypic/cache directory. -**Validates: Requirements 6.1** - -### Property 13: Cache used when valid -*For any* library switch where valid cache exists (cache timestamp >= db modification timestamp), the images should be loaded from cache without database query. -**Validates: Requirements 6.2** - -### Property 14: Cache validation compares timestamps -*For any* cache validation operation, the system should compare the cache's dbModifiedAt timestamp with the current database modification timestamp. -**Validates: Requirements 6.3** - -### Property 15: Stale cache triggers reload -*For any* cache where dbModifiedAt < current database modification timestamp, the cache should be invalidated and data should be reloaded from database. -**Validates: Requirements 6.4** - -### Property 16: Folder cache creation -*For any* folder whose images are fully loaded, a separate cache file should be created for that folder. -**Validates: Requirements 7.1** - -### Property 17: Folder cache invalidation on content change -*For any* folder whose content changes (images added/removed), the folder's cache should be invalidated on next access. -**Validates: Requirements 7.3** - -### Property 18: LRU cache eviction -*For any* state where folder cache count exceeds the maximum threshold, the least recently used folder cache should be evicted first. -**Validates: Requirements 7.4** + ## Error Handling @@ -450,12 +254,7 @@ flowchart TD - 测试请求取消功能 - 测试按类型取消请求 -2. **CacheService 测试** - - 测试缓存文件读写 - - 测试缓存验证逻辑 - - 测试缓存失效判断 - -3. **ImageLoadService 测试** +2. **ImageLoadService 测试** - 测试分批加载逻辑 - 测试空闲加载触发 @@ -468,10 +267,6 @@ flowchart TD - Property 8: 生成请求序列,取消部分,验证回调行为 - Property 9: 生成乱序完成的请求,验证只应用最新结果 -2. **缓存属性测试** - - Property 14/15: 生成随机时间戳组合,验证缓存验证逻辑 - - Property 18: 生成随机访问序列,验证 LRU 驱逐顺序 - ### 集成测试 1. **素材库切换流程测试** @@ -480,5 +275,4 @@ flowchart TD 2. **文件夹导航测试** - 模拟快速点击多个文件夹,验证 debounce 和取消逻辑 -3. **缓存集成测试** - - 测试完整的缓存创建、读取、失效流程 + diff --git a/.kiro/specs/library-switch-optimization/requirements.md b/.kiro/specs/library-switch-optimization/requirements.md index 66d81df..d29a07b 100644 --- a/.kiro/specs/library-switch-optimization/requirements.md +++ b/.kiro/specs/library-switch-optimization/requirements.md @@ -70,26 +70,8 @@ 2. WHEN images are being loaded in batches THEN the System SHALL update the display incrementally as each batch completes 3. WHEN all images are loaded THEN the System SHALL hide the progress indicator -### Requirement 6 - -**User Story:** As a user, I want the application to remember my library data between sessions, so that switching libraries is instant without re-querying the database. - -#### Acceptance Criteria - -1. WHEN a library's image list is fully loaded THEN the System SHALL cache the image metadata to a local file in the .flypic folder -2. WHEN switching to a library with existing cache THEN the System SHALL load from cache file first and display within 200ms -3. WHEN cache exists THEN the System SHALL verify cache validity by comparing database modification timestamp -4. WHEN cache is stale (database modified after cache) THEN the System SHALL invalidate cache and reload from database -5. WHEN new images are added or removed THEN the System SHALL update the cache file incrementally - -### Requirement 7 - -**User Story:** As a user, I want folder-level caching, so that clicking on previously visited folders is instant. - -#### Acceptance Criteria - -1. WHEN a folder's images are loaded THEN the System SHALL cache that folder's image list separately -2. WHEN clicking a cached folder THEN the System SHALL display cached images immediately -3. WHEN the folder's content changes THEN the System SHALL detect the change and refresh the cache -4. WHEN memory usage exceeds threshold THEN the System SHALL evict least recently used folder caches + diff --git a/.kiro/specs/library-switch-optimization/tasks.md b/.kiro/specs/library-switch-optimization/tasks.md index bdceb81..6405032 100644 --- a/.kiro/specs/library-switch-optimization/tasks.md +++ b/.kiro/specs/library-switch-optimization/tasks.md @@ -40,190 +40,95 @@ - **Property 8: Cancelled requests don't trigger callbacks** - **Validates: Requirements 4.2** -- [x] 3. 前端缓存服务 - CacheService + - - [x] 3.1 创建 CacheService 服务 - - - - 新建 `frontend/src/services/cacheService.js` - - 实现缓存读取、写入、验证方法 - - 使用 localStorage 或 IndexedDB 存储缓存元数据 - - _Requirements: 6.1, 6.2_ - - [x] 3.2 实现缓存验证逻辑 - - - 比较缓存时间戳与数据库修改时间 - - 实现缓存失效判断 - - _Requirements: 6.3, 6.4_ - - [x] 3.3 编写缓存验证属性测试 - - - - **Property 14: Cache validation compares timestamps** - - **Property 15: Stale cache triggers reload** - - **Validates: Requirements 6.3, 6.4** - -- [x] 4. 后端缓存文件管理 - - - [x] 4.1 创建缓存文件读写工具 - - - - 新建 `backend/utils/cacheManager.js` - - 实现 `.flypic/cache/` 目录下的文件读写 - - _Requirements: 6.1, 7.1_ - - [x] 4.2 添加缓存 API 路由 - - - - 新建 `backend/routes/cache.js` - - GET `/api/cache/library/:libraryId` - 获取素材库缓存 - - POST `/api/cache/library/:libraryId` - 保存素材库缓存 - - GET `/api/cache/folder/:libraryId/:folderHash` - 获取文件夹缓存 - - _Requirements: 6.1, 6.2, 7.1, 7.2_ - - [x] 4.3 编写缓存文件创建属性测试 - - - - **Property 12: Cache file creation after full load** - - **Property 16: Folder cache creation** - - **Validates: Requirements 6.1, 7.1** - -- [x] 5. Checkpoint - 确保基础设施测试通过 +- [x] 3. Checkpoint - 确保基础设施测试通过 - Ensure all tests pass, ask the user if questions arise. -- [x] 6. 前端图片加载服务 - ImageLoadService - - - [x] 6.1 创建 ImageLoadService 服务 - +- [x] 4. 前端图片加载服务 - ImageLoadService + - [x] 4.1 创建 ImageLoadService 服务 - 新建 `frontend/src/services/imageLoadService.js` - - 实现 `loadInitialBatch`、`loadNextBatch` 方法 + - 实现 `loadNextBatch` 方法 - 集成 RequestManager 进行请求管理 - _Requirements: 2.1, 2.3_ - - [x] 6.2 实现空闲加载逻辑 + - [x] 4.2 实现空闲加载逻辑 - 使用 `requestIdleCallback` 或 `setTimeout` 实现空闲检测 - 在空闲时继续加载剩余图片 - _Requirements: 2.4_ - - [x] 6.3 实现缓存优先加载 - - 切换素材库/文件夹时先检查缓存 - - 缓存有效则直接使用,无效则从 API 加载 - - _Requirements: 6.2, 7.2_ - - [x] 6.4 编写分批加载属性测试 + - [x] 4.3 编写分批加载属性测试 - **Property 4: Scroll triggers batch loading** - **Property 11: Batch loading updates display incrementally** - **Validates: Requirements 2.3, 5.2** -- [x] 7. 重构 Sidebar 组件 - 素材库切换 - - - [x] 7.1 重构 handleLibraryClick 函数 - +- [x] 5. 重构 Sidebar 组件 - 素材库切换 + - [x] 5.1 重构 handleLibraryClick 函数 - 集成 RequestManager 取消之前的请求 - 清理之前素材库的状态 - - 优先从缓存加载 - - _Requirements: 1.2, 1.3, 6.2_ - - [x] 7.2 编写素材库切换属性测试 + - _Requirements: 1.2, 1.3_ + + - [x] 5.2 编写素材库切换属性测试 - **Property 1: Request cancellation on library switch** - **Property 2: Memory cleanup on library switch** - **Validates: Requirements 1.2, 1.3** -- [x] 8. 重构 MainContent 组件 - 文件夹切换 +- [x] 6. 重构 MainContent 组件 - 文件夹切换 - - - [x] 8.1 重构 loadImages 函数 - - - 集成 ImageLoadService 进行分批加载 + - [x] 6.1 重构 loadImages 函数 - 实现请求取消和 debounce - _Requirements: 2.1, 2.2, 3.2_ - - [x] 8.2 添加加载进度显示 - + - [x] 6.2 添加加载进度显示 - 显示已加载/总数 - 加载完成后隐藏进度条 - _Requirements: 5.1, 5.2, 5.3_ - - [x] 8.3 编写文件夹切换属性测试 + + - [x] 6.3 编写文件夹切换属性测试 - **Property 3: Request cancellation on folder switch** - **Property 5: Debounce rapid folder clicks** - **Validates: Requirements 2.2, 3.2** -- [x] 9. 重构 ImageWaterfall 组件 - 滚动加载 - - - [x] 9.1 添加滚动加载触发 - +- [x] 7. 重构 ImageWaterfall 组件 - 滚动加载 + - [x] 7.1 添加滚动加载触发 - 监听滚动事件,接近底部时触发加载下一批 - 集成 ImageLoadService - _Requirements: 2.3_ - - [x] 9.2 优化大数据量渲染 - - + - [x] 7.2 优化大数据量渲染 - 确保虚拟滚动正确处理增量数据 - 优化 Worker 数据传输 - _Requirements: 3.1_ -- [x] 10. Store 状态扩展 - - - [x] 10.1 添加加载状态字段 - +- [x] 8. Store 状态扩展 + - [x] 8.1 添加加载状态字段 - 添加 `isLoadingImages`、`loadedImageCount`、`hasMoreImages` 等字段 - - 添加 `currentLoadContext` 跟踪当前加载上下文 - _Requirements: 4.3, 5.1_ - - [x] 10.2 编写状态管理属性测试 + - [x] 8.2 编写状态管理属性测试 - **Property 9: Only latest request result applied** - **Validates: Requirements 4.3** -- [x] 11. Checkpoint - 确保核心功能测试通过 - - - Ensure all tests pass, ask the user if questions arise. - -- [x] 12. 缓存生命周期管理 - - - [x] 12.1 实现缓存自动保存 - - - 图片加载完成后自动保存缓存 - - 增量更新缓存(新增/删除图片时) - - _Requirements: 6.1, 6.5_ - - - [x] 12.2 实现 LRU 缓存驱逐 - - 跟踪文件夹缓存访问时间 - - 超过阈值时驱逐最久未使用的缓存 - - _Requirements: 7.4_ - - - [ ]* 12.3 编写 LRU 驱逐属性测试 - - **Property 18: LRU cache eviction** - - **Validates: Requirements 7.4** - -- [x] 13. 组件卸载清理 - - [x] 13.1 添加组件卸载时的请求取消 - +- [x] 9. 组件卸载清理 + - [x] 9.1 添加组件卸载时的请求取消 - 在 MainContent、ImageWaterfall 的 useEffect cleanup 中取消请求 - _Requirements: 4.4_ - - [ ]* 13.2 编写卸载清理属性测试 - - **Property 10: Unmount cancels all requests** - - **Validates: Requirements 4.4** - - - - -- [x] 14. 空闲加载与用户操作协调 - - [x] 14.1 实现空闲加载暂停机制 +- [x] 10. 空闲加载与用户操作协调 + - [x] 10.1 实现空闲加载暂停机制 - 用户操作时暂停空闲加载 - - 操作完成后恢复空闲加载 - _Requirements: 3.3_ - - [ ]* 14.2 编写空闲加载协调属性测试 - - **Property 6: Background loading pauses on user action** - - **Validates: Requirements 3.3** - - -- [x] 15. Final Checkpoint - 确保所有测试通过 +- [x] 11. Final Checkpoint - 确保所有测试通过 - Ensure all tests pass, ask the user if questions arise. diff --git a/backend/routes/library.js b/backend/routes/library.js index f7ea0ec..f26e5b8 100644 --- a/backend/routes/library.js +++ b/backend/routes/library.js @@ -1,7 +1,6 @@ const express = require('express'); const router = express.Router(); const fs = require('fs'); -const path = require('path'); const { loadConfig, addLibrary, @@ -142,7 +141,6 @@ router.post('/:id/set-current', async (req, res) => { const { id } = req.params; const config = loadConfig(); const dbPool = require('../database/dbPool'); - const fileWatcher = require('../utils/fileWatcher'); const scanManager = require('../utils/scanManager'); // 获取旧的当前素材库 diff --git a/frontend/src/components/ImageWaterfall.jsx b/frontend/src/components/ImageWaterfall.jsx index be90db6..ea65040 100644 --- a/frontend/src/components/ImageWaterfall.jsx +++ b/frontend/src/components/ImageWaterfall.jsx @@ -1,11 +1,11 @@ import { useState, useEffect, useRef, useMemo, useCallback } from 'react'; -import { PhotoProvider, PhotoView } from 'react-photo-view'; +import { PhotoProvider } 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 imageLoadService from '../services/imageLoadService'; +import requestManager, { RequestType } from '../services/requestManager'; import FileViewer from './FileViewer'; // 虚拟滚动阈值:超过此数量启用虚拟滚动 @@ -26,7 +26,12 @@ function ImageWaterfall() { toggleImageSelection, clearSelection, isResizingPanels, - imageLoadingState + imageLoadingState, + selectedFolder, + searchKeywords, + filters, + appendImages, + setImageLoadingState } = useStore(); const containerRef = useRef(null); const listRef = useRef(null); @@ -39,6 +44,52 @@ function ImageWaterfall() { const [viewerFile, setViewerFile] = useState(null); const [workerRows, setWorkerRows] = useState([]); // Worker 计算的行 + // 加载更多图片 + const loadMoreImages = useCallback(async () => { + if (!currentLibraryId || !imageLoadingState.hasMore || imageLoadingState.isLoading) { + return; + } + + const requestContext = requestManager.createRequest(RequestType.IMAGES); + setImageLoadingState({ isLoading: true }); + + try { + const params = { + offset: imageLoadingState.loadedCount, + limit: 200 + }; + if (selectedFolder) params.folder = selectedFolder; + if (searchKeywords) params.keywords = searchKeywords; + if (filters.formats?.length > 0) params.formats = filters.formats.join(','); + + const response = await imageAPI.search(currentLibraryId, params, { + signal: requestContext.signal + }); + + if (!requestManager.isValid(requestContext.id)) { + return; + } + + const { images, total, hasMore } = response.data; + requestManager.complete(requestContext.id); + + appendImages(images); + setImageLoadingState({ + isLoading: false, + loadedCount: imageLoadingState.loadedCount + images.length, + totalCount: total, + hasMore: hasMore || false + }); + } catch (error) { + if (error.name === 'CanceledError' || error.name === 'AbortError') { + return; + } + console.error('Error loading more images:', error); + requestManager.error(requestContext.id); + setImageLoadingState({ isLoading: false }); + } + }, [currentLibraryId, imageLoadingState, selectedFolder, searchKeywords, filters, appendImages, setImageLoadingState]); + // 监听容器宽度变化(使用 ResizeObserver + 去抖/阈值抑制) useEffect(() => { let resizeObserver = null; @@ -533,7 +584,7 @@ function ImageWaterfall() { const scrollBottom = scrollOffset + (containerHeight || 600); // 距离底部 500px 时触发加载 if (totalHeight - scrollBottom < 500) { - imageLoadService.loadNextBatch(); + loadMoreImages(); } } }} @@ -549,7 +600,7 @@ function ImageWaterfall() { if (imageLoadingState.hasMore && !imageLoadingState.isLoading) { const { scrollTop, scrollHeight, clientHeight } = e.target; if (scrollHeight - scrollTop - clientHeight < 500) { - imageLoadService.loadNextBatch(); + loadMoreImages(); } } }} diff --git a/frontend/src/components/MainContent.jsx b/frontend/src/components/MainContent.jsx index daa96dd..6e36d59 100644 --- a/frontend/src/components/MainContent.jsx +++ b/frontend/src/components/MainContent.jsx @@ -2,7 +2,7 @@ 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 imageLoadService from '../services/imageLoadService'; +import { onUserActionStart, onUserActionEnd } from '../services/imageLoadService'; import requestManager, { RequestType } from '../services/requestManager'; import ImageWaterfall from './ImageWaterfall'; import Dashboard from './Dashboard'; @@ -63,7 +63,7 @@ function MainContent() { } // 暂停空闲加载并取消之前的所有请求(关键!) - imageLoadService.onUserActionStart(); + onUserActionStart(); cancelCurrentRequest(); // 使用 requestManager 创建请求上下文 @@ -110,7 +110,7 @@ function MainContent() { // 如果还有更多数据,恢复空闲加载 if (hasMore) { - imageLoadService.onUserActionEnd(); + onUserActionEnd(hasMore); } } catch (error) { diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx index 9ed666b..28fe9da 100644 --- a/frontend/src/components/Sidebar.jsx +++ b/frontend/src/components/Sidebar.jsx @@ -2,8 +2,8 @@ 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'; -import requestManager, { RequestType } from '../services/requestManager'; -import imageLoadService from '../services/imageLoadService'; +import requestManager from '../services/requestManager'; +import { onUserActionStart } from '../services/imageLoadService'; // 检查素材库是否有暂停的扫描 const checkPausedScan = async (libraryId) => { @@ -156,7 +156,7 @@ function Sidebar() { setIsSwitching(true); try { // 1. 暂停空闲加载并取消所有之前的请求 - imageLoadService.onUserActionStart(); + onUserActionStart(); requestManager.cancelAllRequests(); // 2. 清理当前素材库的状态(立即响应) @@ -388,7 +388,7 @@ function Sidebar() { // 如果是第一次点击(未选中),则选中 if (selectedFolder !== folder.path) { // 暂停空闲加载 - imageLoadService.onUserActionStart(); + onUserActionStart(); setSelectedFolder(folder.path); } else if (hasChildren) { // 如果已经选中,且有子文件夹,则展开/折叠 diff --git a/frontend/src/services/imageLoadService.js b/frontend/src/services/imageLoadService.js index ac1c926..3272271 100644 --- a/frontend/src/services/imageLoadService.js +++ b/frontend/src/services/imageLoadService.js @@ -1,179 +1,76 @@ /** - * ImageLoadService - 图片分批加载服务 - * 支持分页加载、空闲加载 + * ImageLoadService - 图片加载工具函数集合 + * 提供空闲加载控制,状态由 Store 统一管理 */ -import { imageAPI } from './api'; import requestManager, { RequestType } from './requestManager'; -// 默认批次大小 -const DEFAULT_BATCH_SIZE = 200; +// 空闲加载定时器 +let idleTimer = null; +// 空闲加载是否暂停 +let idlePaused = false; -// 空闲加载延迟(毫秒) -const IDLE_LOAD_DELAY = 500; +/** + * 用户操作开始时调用,暂停空闲加载并取消所有进行中的请求 + */ +export function onUserActionStart() { + pauseIdleLoading(); + requestManager.cancelAll(RequestType.IMAGES); +} -class ImageLoadService { - constructor() { - // 当前加载状态 - this.state = { - libraryId: null, - folder: null, - images: [], - offset: 0, - total: 0, - hasMore: false, - isLoading: false - }; - - // 空闲加载定时器 - this.idleTimer = null; - // 空闲加载是否暂停 - this.idlePaused = false; - } - - /** - * 用户操作开始时调用,暂停空闲加载并取消所有进行中的请求 - */ - onUserActionStart() { - this.pauseIdleLoading(); - requestManager.cancelAll(RequestType.IMAGES); - } - - /** - * 用户操作结束时调用,恢复空闲加载 - */ - onUserActionEnd() { +/** + * 用户操作结束时调用,恢复空闲加载 + * @param {boolean} hasMore - 是否还有更多数据 + */ +export function onUserActionEnd(hasMore) { + if (hasMore) { setTimeout(() => { - if (this.state.hasMore && !this.state.isLoading) { - this.resumeIdleLoading(); - } + resumeIdleLoading(); }, 300); } - - /** - * 加载下一批图片 - */ - async loadNextBatch(batchSize = DEFAULT_BATCH_SIZE) { - if (!this.state.hasMore || this.state.isLoading) { - return null; - } - - const { libraryId, folder, offset, images } = this.state; - const requestContext = requestManager.createRequest(RequestType.IMAGES); - - this.state.isLoading = true; - - try { - const params = { offset, limit: batchSize }; - if (folder) params.folder = folder; - - const response = await imageAPI.search(libraryId, params, { - signal: requestContext.signal - }); - - if (!requestManager.isValid(requestContext.id)) { - return null; - } - - const newImages = response.data.images; - const allImages = [...images, ...newImages]; - - this.state = { - ...this.state, - images: allImages, - offset: allImages.length, - total: response.data.total, - hasMore: response.data.hasMore, - isLoading: false - }; - - requestManager.complete(requestContext.id); - - return { - images: newImages, - total: response.data.total, - hasMore: response.data.hasMore - }; - } catch (error) { - if (error.name === 'CanceledError' || error.name === 'AbortError') { - return null; - } - requestManager.error(requestContext.id); - this.state.isLoading = false; - throw error; - } - } - - /** - * 启动空闲加载 - */ - startIdleLoading() { - if (this.idleTimer || this.idlePaused) return; - - const loadNext = async () => { - if (this.idlePaused || !this.state.hasMore) return; - - try { - await this.loadNextBatch(); - - if (this.state.hasMore && !this.idlePaused) { - if (typeof requestIdleCallback !== 'undefined') { - this.idleTimer = requestIdleCallback(() => { - this.idleTimer = null; - loadNext(); - }, { timeout: 2000 }); - } else { - this.idleTimer = setTimeout(() => { - this.idleTimer = null; - loadNext(); - }, IDLE_LOAD_DELAY); - } - } - } catch (error) { - console.error('Idle loading error:', error); - } - }; - - this.idleTimer = setTimeout(() => { - this.idleTimer = null; - loadNext(); - }, IDLE_LOAD_DELAY); - } - - /** - * 暂停空闲加载 - */ - pauseIdleLoading() { - this.idlePaused = true; - this.cancelIdleLoading(); - } - - /** - * 恢复空闲加载 - */ - resumeIdleLoading() { - this.idlePaused = false; - if (this.state.hasMore) { - this.startIdleLoading(); - } - } - - /** - * 取消空闲加载 - */ - cancelIdleLoading() { - if (this.idleTimer) { - if (typeof cancelIdleCallback !== 'undefined') { - cancelIdleCallback(this.idleTimer); - } else { - clearTimeout(this.idleTimer); - } - this.idleTimer = null; - } - } } -// 单例实例 -const imageLoadService = new ImageLoadService(); +/** + * 暂停空闲加载 + */ +export function pauseIdleLoading() { + idlePaused = true; + cancelIdleLoading(); +} -export default imageLoadService; -export { ImageLoadService, DEFAULT_BATCH_SIZE }; +/** + * 恢复空闲加载 + */ +export function resumeIdleLoading() { + idlePaused = false; +} + +/** + * 取消空闲加载定时器 + */ +export function cancelIdleLoading() { + if (idleTimer) { + if (typeof cancelIdleCallback !== 'undefined') { + cancelIdleCallback(idleTimer); + } else { + clearTimeout(idleTimer); + } + idleTimer = null; + } +} + +/** + * 检查空闲加载是否暂停 + */ +export function isIdlePaused() { + return idlePaused; +} + +// 默认导出兼容旧代码 +export default { + onUserActionStart, + onUserActionEnd, + pauseIdleLoading, + resumeIdleLoading, + cancelIdleLoading, + isIdlePaused +}; diff --git a/frontend/src/services/imageLoadService.test.js b/frontend/src/services/imageLoadService.test.js index 3c02ea6..99cfa85 100644 --- a/frontend/src/services/imageLoadService.test.js +++ b/frontend/src/services/imageLoadService.test.js @@ -7,27 +7,18 @@ */ import { describe, it, expect, beforeEach, vi } from 'vitest'; import * as fc from 'fast-check'; -import { ImageLoadService, DEFAULT_BATCH_SIZE } from './imageLoadService.js'; - -// Mock dependencies -vi.mock('./api', () => ({ - imageAPI: { - search: vi.fn(), - getCacheMeta: vi.fn() - } -})); +import { + onUserActionStart, + onUserActionEnd, + pauseIdleLoading, + resumeIdleLoading, + isIdlePaused +} from './imageLoadService.js'; +// Mock requestManager vi.mock('./requestManager', () => ({ default: { - createRequest: vi.fn(() => ({ - id: `req_${Date.now()}`, - signal: new AbortController().signal, - isActive: true - })), - cancelAll: vi.fn(), - isValid: vi.fn().mockReturnValue(true), - complete: vi.fn(), - error: vi.fn() + cancelAll: vi.fn() }, RequestType: { LIBRARY: 'library', @@ -36,33 +27,34 @@ vi.mock('./requestManager', () => ({ } })); -describe('ImageLoadService', () => { - let service; +// 默认批次大小(用于属性测试) +const DEFAULT_BATCH_SIZE = 200; +describe('ImageLoadService', () => { beforeEach(() => { - service = new ImageLoadService(); vi.clearAllMocks(); + // 重置空闲加载状态 + resumeIdleLoading(); }); /** * **Property 4: Scroll triggers batch loading** + * 测试 Store 状态管理逻辑(hasMore 标志) */ describe('Property 4: Scroll triggers batch loading', () => { - it('should set hasMore=true when total exceeds loaded count', () => { + it('should correctly determine hasMore based on loaded vs total count', () => { fc.assert( fc.property( fc.integer({ min: DEFAULT_BATCH_SIZE + 1, max: 10000 }), (totalImages) => { - service.state = { - ...service.state, - images: Array(DEFAULT_BATCH_SIZE).fill({ id: 1 }), - offset: DEFAULT_BATCH_SIZE, - total: totalImages, - hasMore: true + // 模拟 Store 状态 + const state = { + loadedCount: DEFAULT_BATCH_SIZE, + totalCount: totalImages, + hasMore: DEFAULT_BATCH_SIZE < totalImages }; - return service.state.hasMore === true && - service.state.offset < service.state.total; + return state.hasMore === true && state.loadedCount < state.totalCount; } ), { numRuns: 100 } @@ -74,16 +66,14 @@ describe('ImageLoadService', () => { fc.property( fc.integer({ min: 1, max: DEFAULT_BATCH_SIZE }), (totalImages) => { - service.state = { - ...service.state, - images: Array(totalImages).fill({ id: 1 }), - offset: totalImages, - total: totalImages, + // 模拟 Store 状态 + const state = { + loadedCount: totalImages, + totalCount: totalImages, hasMore: false }; - return service.state.hasMore === false && - service.state.offset === service.state.total; + return state.hasMore === false && state.loadedCount === state.totalCount; } ), { numRuns: 100 } @@ -101,26 +91,12 @@ describe('ImageLoadService', () => { fc.integer({ min: 0, max: 5000 }), fc.integer({ min: 1, max: DEFAULT_BATCH_SIZE }), (initialCount, batchSize) => { + // 模拟 Store 的 appendImages 行为 const initialImages = Array(initialCount).fill({ id: 1 }); const newImages = Array(batchSize).fill({ id: 2 }); + const allImages = [...initialImages, ...newImages]; - service.state = { - ...service.state, - images: initialImages, - offset: initialCount - }; - - const prevCount = service.state.images.length; - - service.state = { - ...service.state, - images: [...initialImages, ...newImages], - offset: initialCount + batchSize - }; - - const newCount = service.state.images.length; - - return newCount === prevCount + batchSize; + return allImages.length === initialCount + batchSize; } ), { numRuns: 100 } @@ -129,22 +105,45 @@ describe('ImageLoadService', () => { }); describe('Idle loading control', () => { - it('should pause and resume idle loading', () => { - service.state.hasMore = true; - - service.pauseIdleLoading(); - expect(service.idlePaused).toBe(true); - - service.resumeIdleLoading(); - expect(service.idlePaused).toBe(false); + it('should pause idle loading on user action start', () => { + expect(isIdlePaused()).toBe(false); + + onUserActionStart(); + + expect(isIdlePaused()).toBe(true); }); - it('should cancel idle loading', () => { - service.idleTimer = setTimeout(() => {}, 10000); + it('should track pause state correctly', () => { + pauseIdleLoading(); + expect(isIdlePaused()).toBe(true); - service.cancelIdleLoading(); + resumeIdleLoading(); + expect(isIdlePaused()).toBe(false); + }); - expect(service.idleTimer).toBe(null); + it('should handle multiple pause/resume cycles', () => { + fc.assert( + fc.property( + fc.array(fc.boolean(), { minLength: 1, maxLength: 20 }), + (actions) => { + // 重置状态 + resumeIdleLoading(); + + for (const shouldPause of actions) { + if (shouldPause) { + pauseIdleLoading(); + if (!isIdlePaused()) return false; + } else { + resumeIdleLoading(); + if (isIdlePaused()) return false; + } + } + + return true; + } + ), + { numRuns: 100 } + ); }); }); }); diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js index 2c2993d..350eb42 100644 --- a/frontend/src/store/useStore.js +++ b/frontend/src/store/useStore.js @@ -28,11 +28,9 @@ const useStore = create((set, get) => ({ // 图片加载状态(用于分批加载) imageLoadingState: { isLoading: false, - isIdleLoading: false, loadedCount: 0, totalCount: 0, - hasMore: false, - currentRequestId: null + hasMore: false }, setImageLoadingState: (state) => set((prev) => ({ imageLoadingState: { ...prev.imageLoadingState, ...state }