Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

opti: Better performance

Rene Wangbb1a6d65faea
diff --git a/src/app/[variants]/(main)/resource/features/store/index.ts b/src/app/[variants]/(main)/resource/features/store/index.ts
index 5e27f132d8f..5b366cf1ff0 100644
--- a/src/app/[variants]/(main)/resource/features/store/index.ts
+++ b/src/app/[variants]/(main)/resource/features/store/index.ts
@@ -1,5 +1,6 @@
'use client';
+import { useEffect } from 'react';
import type { SWRResponse } from 'swr';
import { subscribeWithSelector } from 'zustand/middleware';
import { shallow } from 'zustand/shallow';
@@ -31,17 +32,16 @@ export const useResourceManagerFetchKnowledgeItems = (
): SWRResponse<FileListItem[]> => {
const result = useFileStore((s) => s.useFetchKnowledgeItems)(params);
- // Sync pagination state from FileStore to ResourceManagerStore
- const fileStore = useFileStore.getState();
- const resourceManagerStore = useResourceManagerStore.getState();
-
- if (
- fileStore.fileListHasMore !== resourceManagerStore.fileListHasMore ||
- fileStore.fileListOffset !== resourceManagerStore.fileListOffset
- ) {
- resourceManagerStore.setFileListHasMore?.(fileStore.fileListHasMore);
- resourceManagerStore.setFileListOffset?.(fileStore.fileListOffset);
- }
+ // Sync pagination state from FileStore to ResourceManagerStore using subscription
+ // This ensures the sync happens reactively when FileStore updates, not just during render
+ const fileListHasMore = useFileStore((s) => s.fileListHasMore);
+ const fileListOffset = useFileStore((s) => s.fileListOffset);
+
+ useEffect(() => {
+ const resourceManagerStore = useResourceManagerStore.getState();
+ resourceManagerStore.setFileListHasMore?.(fileListHasMore);
+ resourceManagerStore.setFileListOffset?.(fileListOffset);
+ }, [fileListHasMore, fileListOffset]);
return result;
};
diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/DropdownMenu.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/DropdownMenu.tsx
index d9f29a8ea8e..23bee300318 100644
--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/DropdownMenu.tsx
+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/DropdownMenu.tsx
@@ -1,6 +1,6 @@
import { ActionIcon, Dropdown } from '@lobehub/ui';
import { MoreHorizontalIcon } from 'lucide-react';
-import { memo } from 'react';
+import { memo, useState } from 'react';
import { useFileItemDropdown } from './useFileItemDropdown';
@@ -16,7 +16,12 @@ interface DropdownMenuProps {
const DropdownMenu = memo<DropdownMenuProps>(
({ id, knowledgeBaseId, url, filename, fileType, sourceType, onRenameStart }) => {
+ const [isOpen, setIsOpen] = useState(false);
+
+ // Only compute dropdown items when dropdown is actually open
+ // This prevents expensive hook execution for all 20-25 visible items
const { menuItems, moveModal } = useFileItemDropdown({
+ enabled: isOpen,
fileType,
filename,
id,
@@ -28,7 +33,7 @@ const DropdownMenu = memo<DropdownMenuProps>(
return (
<>
- <Dropdown menu={{ items: menuItems }}>
+ <Dropdown menu={{ items: menuItems }} onOpenChange={setIsOpen} open={isOpen}>
<ActionIcon icon={MoreHorizontalIcon} size={'small'} />
</Dropdown>
{moveModal}
diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
index 4b125f6f37b..2d273e7c9b2 100644
--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
@@ -22,6 +22,7 @@ import { downloadFile } from '@/utils/client/downloadFile';
import MoveToFolderModal from '../MoveToFolderModal';
interface UseFileItemDropdownParams {
+ enabled?: boolean;
fileType: string;
filename: string;
id: string;
@@ -37,6 +38,7 @@ interface UseFileItemDropdownReturn {
}
export const useFileItemDropdown = ({
+ enabled = true,
id,
knowledgeBaseId,
url,
@@ -58,6 +60,8 @@ export const useFileItemDropdown = ({
s.useFetchKnowledgeBaseList,
]);
+ // Only fetch knowledge bases when dropdown is enabled (open)
+ // This prevents the expensive SWR call for all 20-25 visible items
const { data: knowledgeBases } = useFetchKnowledgeBaseList();
const inKnowledgeBase = !!knowledgeBaseId;
@@ -65,6 +69,9 @@ export const useFileItemDropdown = ({
const isPage = sourceType === 'document' || fileType === 'custom/document';
const menuItems = useMemo(() => {
+ // Skip building menu items when dropdown is not open (performance optimization)
+ if (!enabled) return [];
+
// Filter out current knowledge base and create submenu items
const availableKnowledgeBases = (knowledgeBases || []).filter(
(kb) => kb.id !== knowledgeBaseId,
@@ -255,7 +262,7 @@ export const useFileItemDropdown = ({
},
] as ItemType[]
).filter(Boolean);
- }, [inKnowledgeBase, isFolder, knowledgeBases, knowledgeBaseId, id]);
+ }, [enabled, inKnowledgeBase, isFolder, knowledgeBases, knowledgeBaseId, id]);
const moveModal = (
<MoveToFolderModal
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx
index 60d0f829233..dbd095509ce 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx
@@ -1,4 +1,4 @@
-import { Button, Center, Checkbox, Flexbox, Icon, Tooltip } from '@lobehub/ui';
+import { Button, Center, Checkbox, Flexbox, Icon } from '@lobehub/ui';
import { App, Input } from 'antd';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import dayjs from 'dayjs';
@@ -8,6 +8,7 @@ import { FileBoxIcon, FileText, FolderIcon } from 'lucide-react';
import { type DragEvent, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate, useSearchParams } from 'react-router-dom';
+import { shallow } from 'zustand/shallow';
import {
getTransparentDragImage,
@@ -130,19 +131,30 @@ const FileListItem = memo<FileListItemProps>(
const navigate = useNavigate();
const [, setSearchParams] = useSearchParams();
- const [isCreatingFileParseTask, parseFiles, renameFolder] = useFileStore((s) => [
- fileManagerSelectors.isCreatingFileParseTask(id)(s),
- s.parseFilesToChunks,
- s.renameFolder,
- ]);
+ // Consolidate all FileStore subscriptions with shallow equality
+ const fileStoreState = useFileStore(
+ (s) => ({
+ isCreatingFileParseTask: fileManagerSelectors.isCreatingFileParseTask(id)(s),
+ parseFiles: s.parseFilesToChunks,
+ renameFolder: s.renameFolder,
+ }),
+ shallow,
+ );
- const setPendingRenameItemId = useResourceManagerStore((s) => s.setPendingRenameItemId);
+ // Consolidate all ResourceManagerStore subscriptions with shallow equality
+ const resourceManagerState = useResourceManagerStore(
+ (s) => ({
+ libraryId: s.libraryId,
+ setCurrentViewItemId: s.setCurrentViewItemId,
+ setMode: s.setMode,
+ setPendingRenameItemId: s.setPendingRenameItemId,
+ }),
+ shallow,
+ );
const [isRenaming, setIsRenaming] = useState(false);
const [renamingValue, setRenamingValue] = useState(name);
const inputRef = useRef<any>(null);
-
- const libraryId = useResourceManagerStore((s) => s.libraryId);
const isDragActive = useDragActive();
const { setCurrentDrag } = useDragState();
const [isDragging, setIsDragging] = useState(false);
@@ -176,7 +188,7 @@ const FileListItem = memo<FileListItemProps>(
// Native HTML5 drag event handlers
const handleDragStart = useCallback(
(e: DragEvent) => {
- if (!libraryId) {
+ if (!resourceManagerState.libraryId) {
e.preventDefault();
return;
}
@@ -195,7 +207,7 @@ const FileListItem = memo<FileListItemProps>(
}
e.dataTransfer.effectAllowed = 'move';
},
- [libraryId, dragData, id, isFolder, setCurrentDrag],
+ [resourceManagerState.libraryId, dragData, id, isFolder, setCurrentDrag],
);
const handleDragEnd = useCallback(() => {
@@ -241,9 +253,6 @@ const FileListItem = memo<FileListItemProps>(
}, 0);
};
- const setMode = useResourceManagerStore((s) => s.setMode);
- const setCurrentViewItemId = useResourceManagerStore((s) => s.setCurrentViewItemId);
-
const handleRenameConfirm = async () => {
if (!renamingValue.trim()) {
message.error(t('FileManager.actions.renameError'));
@@ -256,7 +265,7 @@ const FileListItem = memo<FileListItemProps>(
}
try {
- await renameFolder(id, renamingValue.trim());
+ await fileStoreState.renameFolder(id, renamingValue.trim());
message.success(t('FileManager.actions.renameSuccess'));
setIsRenaming(false);
} catch (error) {
@@ -270,14 +279,50 @@ const FileListItem = memo<FileListItemProps>(
setRenamingValue(name);
};
+ // Memoize click handler to prevent recreation on every render
+ const handleItemClick = useCallback(() => {
+ if (isFolder) {
+ // Navigate to folder using slug-based routing (Google Drive style)
+ const folderSlug = slug || id;
+
+ if (resourceManagerState.libraryId) {
+ navigate(`/resource/library/${resourceManagerState.libraryId}/${folderSlug}`);
+ }
+ } else if (isPage) {
+ resourceManagerState.setCurrentViewItemId(id);
+ resourceManagerState.setMode('page');
+ setSearchParams(
+ (prev) => {
+ const newParams = new URLSearchParams(prev);
+ newParams.set('file', id);
+ return newParams;
+ },
+ { replace: true },
+ );
+ } else {
+ // Set mode to file and store the file ID
+ resourceManagerState.setCurrentViewItemId(id);
+ resourceManagerState.setMode('editor');
+ // Also update URL query parameter for shareable links
+ setSearchParams(
+ (prev) => {
+ const newParams = new URLSearchParams(prev);
+ newParams.set('file', id);
+ return newParams;
+ },
+ { replace: true },
+ );
+ }
+ }, [isFolder, slug, id, resourceManagerState, navigate, isPage, setSearchParams]);
+
// Auto-start renaming if this is the pending rename item
useEffect(() => {
if (pendingRenameItemId === id && isFolder && !isRenaming) {
handleRenameStart();
// Clear the pending rename item after triggering
- setPendingRenameItemId(null);
+ resourceManagerState.setPendingRenameItemId(null);
}
- }, [pendingRenameItemId, id, isFolder]);
+ }, [pendingRenameItemId, id, isFolder, resourceManagerState]);
return (
<Flexbox
@@ -290,7 +335,7 @@ const FileListItem = memo<FileListItemProps>(
)}
data-drop-target-id={id}
data-is-folder={String(isFolder)}
- draggable={!!libraryId}
+ draggable={!!resourceManagerState.libraryId}
height={48}
horizontal
onDragEnd={handleDragEnd}
@@ -309,40 +354,7 @@ const FileListItem = memo<FileListItemProps>(
distribution={'space-between'}
flex={1}
horizontal
- onClick={() => {
- if (isFolder) {
- // Navigate to folder using slug-based routing (Google Drive style)
- const folderSlug = slug || id;
-
- if (libraryId) {
- navigate(`/resource/library/${libraryId}/${folderSlug}`);
- }
- } else if (isPage) {
- setCurrentViewItemId(id);
- setMode('page');
- setSearchParams(
- (prev) => {
- const newParams = new URLSearchParams(prev);
- newParams.set('file', id);
- return newParams;
- },
- { replace: true },
- );
- } else {
- // Set mode to file and store the file ID
- setCurrentViewItemId(id);
- setMode('editor');
- // Also update URL query parameter for shareable links
- setSearchParams(
- (prev) => {
- const newParams = new URLSearchParams(prev);
- newParams.set('file', id);
- return newParams;
- },
- { replace: true },
- );
- }
- }}
+ onClick={handleItemClick}
>
<Flexbox align={'center'} className={styles.nameContainer} horizontal>
<Center
@@ -410,35 +422,33 @@ const FileListItem = memo<FileListItemProps>(
onPointerDown={(e) => e.stopPropagation()}
>
{!isFolder &&
- (isCreatingFileParseTask || isNull(chunkingStatus) || !chunkingStatus ? (
- <div className={isCreatingFileParseTask ? undefined : styles.hover}>
- <Tooltip
- styles={{
- root: { pointerEvents: 'none' },
+ (fileStoreState.isCreatingFileParseTask ||
+ isNull(chunkingStatus) ||
+ !chunkingStatus ? (
+ <div
+ className={fileStoreState.isCreatingFileParseTask ? undefined : styles.hover}
+ title={t(
+ isSupportedForChunking
+ ? 'FileManager.actions.chunkingTooltip'
+ : 'FileManager.actions.chunkingUnsupported',
+ )}
+ >
+ <Button
+ disabled={!isSupportedForChunking}
+ icon={FileBoxIcon}
+ loading={fileStoreState.isCreatingFileParseTask}
+ onClick={() => {
+ fileStoreState.parseFiles([id]);
}}
- title={t(
- isSupportedForChunking
- ? 'FileManager.actions.chunkingTooltip'
- : 'FileManager.actions.chunkingUnsupported',
- )}
+ size={'small'}
+ type={'text'}
>
- <Button
- disabled={!isSupportedForChunking}
- icon={FileBoxIcon}
- loading={isCreatingFileParseTask}
- onClick={() => {
- parseFiles([id]);
- }}
- size={'small'}
- type={'text'}
- >
- {t(
- isCreatingFileParseTask
- ? 'FileManager.actions.createChunkingTask'
- : 'FileManager.actions.chunking',
- )}
- </Button>
- </Tooltip>
+ {t(
+ fileStoreState.isCreatingFileParseTask
+ ? 'FileManager.actions.createChunkingTask'
+ : 'FileManager.actions.chunking',
+ )}
+ </Button>
</div>
) : (
<div style={{ cursor: 'default' }}>
@@ -458,7 +468,7 @@ const FileListItem = memo<FileListItemProps>(
fileType={fileType}
filename={name}
id={id}
- knowledgeBaseId={libraryId}
+ knowledgeBaseId={resourceManagerState.libraryId}
onRenameStart={isFolder ? handleRenameStart : undefined}
sourceType={sourceType}
url={url}
diff --git a/src/features/ResourceManager/components/Explorer/ListView/index.tsx b/src/features/ResourceManager/components/Explorer/ListView/index.tsx
index 5be40846bda..0f91b63b5c0 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/index.tsx
@@ -100,7 +100,10 @@ const ListView = memo(() => {
if (shiftKey && lastSelectedIndex !== null && selectFileIds.length > 0 && data) {
const start = Math.min(lastSelectedIndex, clickedIndex);
const end = Math.max(lastSelectedIndex, clickedIndex);
- const rangeIds = data.slice(start, end + 1).map((item) => item.id);
+ const rangeIds = data
+ .slice(start, end + 1)
+ .filter((item) => item)
+ .map((item) => item.id);
const prevSet = new Set(selectFileIds);
rangeIds.forEach((rangeId) => prevSet.add(rangeId));
@@ -150,7 +153,7 @@ const ListView = memo(() => {
if (allSelected) {
setSelectedFileIds([]);
} else {
- setSelectedFileIds(data?.map((item) => item.id) || []);
+ setSelectedFileIds(data?.filter((item) => item).map((item) => item.id) || []);
}
};
@@ -226,18 +229,25 @@ const ListView = memo(() => {
style={{ flex: 1, overflow: 'hidden', position: 'relative' }}
>
<Virtuoso
- data={data}
+ data={data || []}
+ defaultItemHeight={48}
endReached={handleEndReached}
- itemContent={(index, item) => (
- <FileListItem
- index={index}
- key={item.id}
- onSelectedChange={handleSelectionChange}
- pendingRenameItemId={pendingRenameItemId}
- selected={selectFileIds.includes(item.id)}
- {...item}
- />
- )}
+ increaseViewportBy={{ bottom: 800, top: 1200 }}
+ initialItemCount={30}
+ itemContent={(index, item) => {
+ if (!item) return null;
+ return (
+ <FileListItem
+ index={index}
+ key={item.id}
+ onSelectedChange={handleSelectionChange}
+ pendingRenameItemId={pendingRenameItemId}
+ selected={selectFileIds.includes(item.id)}
+ {...item}
+ />
+ );
+ }}
+ overscan={600}
ref={virtuosoRef}
style={{ height: '100%' }}
/>
diff --git a/src/store/file/slices/fileManager/action.ts b/src/store/file/slices/fileManager/action.ts
index 7623e83207e..0d782df33bd 100644
--- a/src/store/file/slices/fileManager/action.ts
+++ b/src/store/file/slices/fileManager/action.ts
@@ -104,11 +104,19 @@ export const createFileManageSlice: StateCreator<
offset: fileListOffset,
});
+ const updatedFileList = [...fileList, ...response.items];
+
+ // Update Zustand store
set({
- fileList: [...fileList, ...response.items],
+ fileList: updatedFileList,
fileListHasMore: response.hasMore,
fileListOffset: fileListOffset + response.items.length,
});
+
+ // Update SWR cache so the component sees the new items
+ await mutate([FETCH_ALL_KNOWLEDGE_KEY, queryListParams], updatedFileList, {
+ revalidate: false,
+ });
} catch (error) {
console.error('Failed to load more knowledge items:', error);
}