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.

⚡️ perf(skill-store): virtualize Skill Store lists with masonic (#23744)

Arvin Xu4236ba937bc3
diff --git a/package.json b/package.json
index 3f4c6d6cd1c..26d8253203c 100644
--- a/package.json
+++ b/package.json
@@ -434,6 +434,7 @@
"lucide-react": "^1.31.0",
"mammoth": "^1.12.1",
"marked": "^17.0.6",
+ "masonic": "^4.1.0",
"mdast-util-to-markdown": "^2.1.2",
"mesurer": "^0.1.0",
"model-bank": "workspace:*",
diff --git a/src/features/SkillStore/SkillList/MCP/index.tsx b/src/features/SkillStore/SkillList/MCP/index.tsx
index e0a8ddeb271..8a052b88da9 100644
--- a/src/features/SkillStore/SkillList/MCP/index.tsx
+++ b/src/features/SkillStore/SkillList/MCP/index.tsx
@@ -4,20 +4,23 @@ import { Center, Flexbox, Icon, Text } from '@lobehub/ui';
import { ServerCrash } from 'lucide-react';
import { memo, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
-import { VirtuosoGrid } from 'react-virtuoso';
import AsyncError from '@/components/AsyncError';
import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';
import { useToolStore } from '@/store/tool';
+import { type DiscoverMcpItem } from '@/types/discover';
import Item from '../Community/Item';
import Empty from '../Empty';
import Loading from '../Loading';
-import { virtuosoGridStyles } from '../style';
+import MasonicGrid from '../MasonicGrid';
import VirtuosoLoading from '../VirtuosoLoading';
import WantMoreSkills from '../WantMoreSkills';
import { canAutoLoadMore, resolveMCPListFooter } from './utils';
+const getPluginKey = (item: DiscoverMcpItem) => item.identifier;
+const renderPlugin = (item: DiscoverMcpItem) => <Item {...item} />;
+
export const MCPList = memo(() => {
const { t } = useTranslation('setting');
@@ -89,16 +92,12 @@ export const MCPList = memo(() => {
};
return (
- <VirtuosoGrid
- components={{ Footer: renderFooter }}
- data={allItems}
- increaseViewportBy={typeof window !== 'undefined' ? window.innerHeight : 0}
- itemClassName={virtuosoGridStyles.item}
- itemContent={(_, item) => <Item {...item} />}
- listClassName={virtuosoGridStyles.list}
- overscan={24}
- style={{ height: '60vh', width: '100%' }}
- endReached={() => {
+ <MasonicGrid
+ footer={renderFooter()}
+ getKey={getPluginKey}
+ items={allItems}
+ renderItem={renderPlugin}
+ onEndReached={() => {
// While a page is failing, paging waits for the explicit retry above
// instead of hammering the endpoint on every scroll.
if (!canAutoLoadMore(list)) return;
diff --git a/src/features/SkillStore/SkillList/MarketSkills/index.tsx b/src/features/SkillStore/SkillList/MarketSkills/index.tsx
index 699c4dd1da9..b7c64ad35d9 100644
--- a/src/features/SkillStore/SkillList/MarketSkills/index.tsx
+++ b/src/features/SkillStore/SkillList/MarketSkills/index.tsx
@@ -4,19 +4,22 @@ import { Button, Center, Flexbox, Icon, Text } from '@lobehub/ui';
import { ServerCrash } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { VirtuosoGrid } from 'react-virtuoso';
import { normalizeAsyncError } from '@/libs/swr/normalizeError';
import { useToolStore } from '@/store/tool';
+import { type DiscoverSkillItem } from '@/types/discover';
import MarketSkillItem from '../Community/MarketSkillItem';
import Empty from '../Empty';
import Loading from '../Loading';
-import { virtuosoGridStyles } from '../style';
+import MasonicGrid from '../MasonicGrid';
import VirtuosoLoading from '../VirtuosoLoading';
import WantMoreSkills from '../WantMoreSkills';
import { useMarketSkillList } from './useMarketSkillList';
+const getSkillKey = (item: DiscoverSkillItem) => item.identifier;
+const renderSkill = (item: DiscoverSkillItem) => <MarketSkillItem {...item} />;
+
interface MarketSkillListProps {
keywords?: string;
}
@@ -79,16 +82,12 @@ const MarketSkillList = memo<MarketSkillListProps>(({ keywords }) => {
};
return (
- <VirtuosoGrid
- components={{ Footer: renderFooter }}
- data={items}
- endReached={loadMore}
- increaseViewportBy={typeof window !== 'undefined' ? window.innerHeight : 0}
- itemClassName={virtuosoGridStyles.item}
- itemContent={(_, item) => <MarketSkillItem {...item} />}
- listClassName={virtuosoGridStyles.list}
- overscan={24}
- style={{ height: '60vh', width: '100%' }}
+ <MasonicGrid
+ footer={renderFooter()}
+ getKey={getSkillKey}
+ items={items}
+ renderItem={renderSkill}
+ onEndReached={loadMore}
/>
);
});
diff --git a/src/features/SkillStore/SkillList/MasonicGrid.tsx b/src/features/SkillStore/SkillList/MasonicGrid.tsx
new file mode 100644
index 00000000000..2bea5fa19c6
--- /dev/null
+++ b/src/features/SkillStore/SkillList/MasonicGrid.tsx
@@ -0,0 +1,221 @@
+'use client';
+
+import { useSize } from 'ahooks';
+import { useMasonry, usePositioner, useResizeObserver } from 'masonic';
+import {
+ type ComponentType,
+ memo,
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
+
+import { useDensityTokens } from '@/styles/density';
+
+import { masonicGridStyles } from './style';
+
+/** Below this width the grid drops to one column, like `responsive.sm`. */
+const SINGLE_COLUMN_WIDTH = 576;
+/** A skill / MCP card: 40px avatar, title and description, padded. */
+const ITEM_HEIGHT_ESTIMATE = 72;
+/** Scroll updates are batched to at most this many renders a second. */
+const SCROLL_FPS = 30;
+/** How long after the last scroll event the list stops counting as scrolling. */
+const SCROLL_IDLE_MS = 150;
+/** How many rows from the end the next page starts loading. */
+const END_THRESHOLD = 8;
+
+interface ScrollState {
+ height: number;
+ isScrolling: boolean;
+ scrollTop: number;
+}
+
+/** The scroll box's position and height, re-read at most `SCROLL_FPS` times a second. */
+const useScrollState = (element: HTMLElement | null) => {
+ const [state, setState] = useState<ScrollState>({ height: 0, isScrolling: false, scrollTop: 0 });
+
+ useEffect(() => {
+ if (!element) return;
+ let frame = 0;
+ let last = 0;
+ let idle: ReturnType<typeof setTimeout> | undefined;
+
+ const read = (isScrolling: boolean) =>
+ setState((prev) => {
+ const next = { height: element.clientHeight, isScrolling, scrollTop: element.scrollTop };
+ return prev.height === next.height &&
+ prev.isScrolling === next.isScrolling &&
+ prev.scrollTop === next.scrollTop
+ ? prev
+ : next;
+ });
+
+ const onScroll = () => {
+ clearTimeout(idle);
+ idle = setTimeout(() => read(false), SCROLL_IDLE_MS);
+ if (frame) return;
+ frame = requestAnimationFrame((now) => {
+ frame = 0;
+ if (now - last < 1000 / SCROLL_FPS) {
+ // Too soon: try again next frame so the last position still lands.
+ onScroll();
+ return;
+ }
+ last = now;
+ read(true);
+ });
+ };
+
+ const resize = new ResizeObserver(() => read(false));
+ resize.observe(element);
+ element.addEventListener('scroll', onScroll, { passive: true });
+ read(false);
+
+ return () => {
+ cancelAnimationFrame(frame);
+ clearTimeout(idle);
+ resize.disconnect();
+ element.removeEventListener('scroll', onScroll);
+ };
+ }, [element]);
+
+ return state;
+};
+
+/**
+ * Bumps when `items` stops extending the previous list. Masonic keeps every
+ * cell's measured position, so a list that shrank or reordered (a new search)
+ * needs a fresh positioner; one that only grew (the next page) keeps them.
+ */
+const useResetVersion = <T,>(items: T[], getKey: (item: T) => string) => {
+ const keys = items.map(getKey);
+ const [seen, setSeen] = useState({ keys, version: 0 });
+ const same =
+ keys.length === seen.keys.length && seen.keys.every((key, index) => key === keys[index]);
+ if (!same) {
+ const grew =
+ keys.length > seen.keys.length && seen.keys.every((key, index) => key === keys[index]);
+ setSeen({ keys, version: grew ? seen.version : seen.version + 1 });
+ }
+ return same ? seen.version : seen.version + 1;
+};
+
+interface MasonicGridProps<T extends object> {
+ /** Below the rows, inside the scroll box: loading, error or end-of-list. */
+ footer?: ReactNode;
+ getKey: (item: T) => string;
+ items: T[];
+ /** Called once per page as the rows near the end of `items` come into view. */
+ onEndReached?: () => void;
+ renderItem: (item: T) => ReactNode;
+}
+
+interface GridProps<T extends object> extends MasonicGridProps<T> {
+ gutter: number;
+ /** Where the grid starts inside the scroll box (the list's top padding). */
+ offset: number;
+ scroll: ScrollState;
+ width: number;
+}
+
+const Grid = <T extends object>({
+ getKey,
+ gutter,
+ items,
+ offset,
+ onEndReached,
+ renderItem,
+ scroll,
+ width,
+}: GridProps<T>) => {
+ const version = useResetVersion(items, getKey);
+ const positioner = usePositioner(
+ {
+ columnCount: width < SINGLE_COLUMN_WIDTH ? 1 : 2,
+ columnGutter: gutter,
+ rowGutter: gutter,
+ width,
+ },
+ [version],
+ );
+ const resizeObserver = useResizeObserver(positioner);
+
+ // Masonic caches each cell element by its render component and data, so cells
+ // read the latest `renderItem` from a ref instead of taking it as a prop.
+ const renderRef = useRef(renderItem);
+ useLayoutEffect(() => {
+ renderRef.current = renderItem;
+ });
+ const Cell = useMemo<ComponentType<{ data: T; index: number; width: number }>>(
+ () =>
+ function SkillStoreGridCell({ data }) {
+ return renderRef.current(data);
+ },
+ [],
+ );
+
+ // One call per length of `items`, so scrolling at the bottom asks for a page once.
+ const requestedAt = useRef(-1);
+ const onRender = useCallback(
+ (_start: number, stop: number, rendered: T[]) => {
+ if (!onEndReached || stop < rendered.length - END_THRESHOLD) return;
+ if (requestedAt.current === rendered.length) return;
+ requestedAt.current = rendered.length;
+ onEndReached();
+ },
+ [onEndReached],
+ );
+
+ return useMasonry({
+ height: scroll.height,
+ isScrolling: scroll.isScrolling,
+ itemHeightEstimate: ITEM_HEIGHT_ESTIMATE,
+ itemKey: getKey,
+ items,
+ onRender,
+ overscanBy: 2,
+ positioner,
+ render: Cell,
+ resizeObserver,
+ role: 'list',
+ scrollTop: Math.max(0, scroll.scrollTop - offset),
+ tabIndex: -1,
+ });
+};
+
+/**
+ * The Skill Store's scrolling two-column card list (masonic): only the cards
+ * near the viewport are mounted, and the next page loads as the end nears.
+ * In a hidden tab (no width yet) it renders no cards at all.
+ */
+const MasonicGrid = <T extends object>({ footer, ...props }: MasonicGridProps<T>) => {
+ const { contentGap } = useDensityTokens();
+ const [scroller, setScroller] = useState<HTMLDivElement | null>(null);
+ const [container, setContainer] = useState<HTMLDivElement | null>(null);
+ const scroll = useScrollState(scroller);
+ const width = useSize(container)?.width ?? 0;
+ const offset = container?.offsetTop ?? 0;
+
+ return (
+ <div
+ ref={setScroller}
+ style={{ height: '60vh', overflowY: 'auto', position: 'relative', width: '100%' }}
+ >
+ <div className={masonicGridStyles.list}>
+ <div ref={setContainer}>
+ {scroll.height > 0 && width > 0 && (
+ <Grid {...props} gutter={contentGap} offset={offset} scroll={scroll} width={width} />
+ )}
+ </div>
+ </div>
+ {footer}
+ </div>
+ );
+};
+
+export default memo(MasonicGrid) as typeof MasonicGrid;
diff --git a/src/features/SkillStore/SkillList/style.ts b/src/features/SkillStore/SkillList/style.ts
index 194ce07ea19..45ea43b272c 100644
--- a/src/features/SkillStore/SkillList/style.ts
+++ b/src/features/SkillStore/SkillList/style.ts
@@ -42,6 +42,13 @@ export const virtuosoGridStyles = createStaticStyles(({ css }) => ({
`,
}));
+export const masonicGridStyles = createStaticStyles(({ css }) => ({
+ list: css`
+ padding-block-end: ${densityVars.cardPadding};
+ padding-inline: ${densityVars.cardPadding};
+ `,
+}));
+
export const itemStyles = createStaticStyles(({ css, cssVar }) => ({
container: css`
position: relative;
diff --git a/src/features/SkillStore/SkillStoreContent.tsx b/src/features/SkillStore/SkillStoreContent.tsx
index 442f48983c2..28bcd177117 100644
--- a/src/features/SkillStore/SkillStoreContent.tsx
+++ b/src/features/SkillStore/SkillStoreContent.tsx
@@ -23,6 +23,9 @@ export const SkillStoreContent = () => {
const [activeTab, setActiveTab] = useState<SkillStoreTab>(SkillStoreTab.LobeHub);
const [lobehubKeywords, setLobehubKeywords] = useState('');
const [skillKeywords, setSkillKeywords] = useState('');
+ // A tab's list mounts (and fetches) on first open, then stays to keep its scroll and pages.
+ const [visited, setVisited] = useState<Set<SkillStoreTab>>(() => new Set([activeTab]));
+ if (!visited.has(activeTab)) setVisited(new Set(visited).add(activeTab));
// Refresh builtin-tool install state for the active workspace whenever the
// modal mounts, so entries opened from contexts that don't host the chat
@@ -64,13 +67,13 @@ export const SkillStoreContent = () => {
</Flexbox>
<Flexbox height={496} style={{ marginBlockEnd: -12, marginInline: -16 }}>
<Flexbox flex={1} style={{ display: isLobeHub ? 'flex' : 'none', overflow: 'auto' }}>
- <LobeHubList keywords={lobehubKeywords} />
+ {visited.has(SkillStoreTab.LobeHub) && <LobeHubList keywords={lobehubKeywords} />}
</Flexbox>
<Flexbox flex={1} style={{ display: isSkills ? 'flex' : 'none', overflow: 'auto' }}>
- <MarketSkillList keywords={skillKeywords} />
+ {visited.has(SkillStoreTab.Skills) && <MarketSkillList keywords={skillKeywords} />}
</Flexbox>
<Flexbox flex={1} style={{ display: isMCP ? 'flex' : 'none', overflow: 'auto' }}>
- <MCPList />
+ {visited.has(SkillStoreTab.MCP) && <MCPList />}
</Flexbox>
</Flexbox>
</Flexbox>