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(resource): keep the drive list smooth when scrolling large folders (#22106)

Rdmclin2919b827fb303
diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/DropdownMenu.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/DropdownMenu.tsx
index 7ebe935e526..d35d1aeedc0 100644
--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/DropdownMenu.tsx
+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/DropdownMenu.tsx
@@ -5,12 +5,14 @@ import { memo } from 'react';
interface DropdownMenuProps {
className?: string;
+ /** Open on mount (the trigger replaced a placeholder that was just activated). */
+ defaultOpen?: boolean;
items: ItemType[] | (() => ItemType[]);
}
-const DropdownMenu = memo<DropdownMenuProps>(({ items, className }) => {
+const DropdownMenu = memo<DropdownMenuProps>(({ items, className, defaultOpen }) => {
return (
- <DropdownMenuUI items={items}>
+ <DropdownMenuUI defaultOpen={defaultOpen} items={items}>
<ActionIcon className={className} icon={MoreHorizontalIcon} size={'small'} />
</DropdownMenuUI>
);
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.test.ts b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.test.ts
index db2b501b066..f4118147f5c 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.test.ts
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.test.ts
@@ -5,18 +5,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import FileListItemActions, { appendTransferMenuItemsBeforeDelete } from './FileListItemActions';
-const mocks = vi.hoisted(() => ({
- useFileTransferMenuItem: vi.fn(),
-}));
-
-vi.mock('@/business/client/hooks/useFileTransferMenuItem', () => ({
- useFileTransferMenuItem: mocks.useFileTransferMenuItem,
-}));
-
-vi.mock('../../ItemDropdown/DropdownMenu', () => ({
- default: () => null,
-}));
-
describe('appendTransferMenuItemsBeforeDelete', () => {
it('keeps delete as the final menu action', () => {
const baseItems = [
@@ -51,22 +39,24 @@ describe('FileListItemActions', () => {
isFolder: false,
isPage: false,
isSupportedForChunking: false,
- menuItems: [],
+ menu: null,
parseFiles: vi.fn(),
t: (key: string) => key,
};
- it('passes document entity type for page resources', () => {
- mocks.useFileTransferMenuItem.mockReturnValue([]);
-
- render(React.createElement(FileListItemActions, { ...baseProps, isPage: true }));
+ it('renders the menu node it is given', () => {
+ render(
+ React.createElement(FileListItemActions, {
+ ...baseProps,
+ menu: React.createElement('span', { 'data-testid': 'row-menu' }),
+ }),
+ );
- expect(mocks.useFileTransferMenuItem).toHaveBeenCalledWith('resource-1', 'document');
+ expect(screen.getByTestId('row-menu')).toBeInTheDocument();
});
it('uses fileId for initial chunk parsing when the resource id is a document id', () => {
const parseFiles = vi.fn();
- mocks.useFileTransferMenuItem.mockReturnValue([]);
render(
React.createElement(FileListItemActions, {
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.tsx
index 59e83336857..b23bbd20e5e 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.tsx
@@ -3,13 +3,11 @@ import type { ItemType } from '@lobehub/ui';
import { Button, Flexbox, stopPropagation } from '@lobehub/ui';
import { isNull } from 'es-toolkit/compat';
import { FileBoxIcon } from 'lucide-react';
-import { useMemo } from 'react';
+import type { ReactNode } from 'react';
-import { useFileTransferMenuItem } from '@/business/client/hooks/useFileTransferMenuItem';
import { usePermission } from '@/hooks/usePermission';
import { getChunkTargetId } from '@/store/file';
-import DropdownMenu from '../../ItemDropdown/DropdownMenu';
import ChunksBadge from './ChunkTag';
import { styles } from './styles';
@@ -26,7 +24,8 @@ interface FileListItemActionsProps {
isFolder: boolean;
isPage: boolean;
isSupportedForChunking: boolean;
- menuItems: ItemType[] | (() => ItemType[]);
+ /** The row's "…" menu, or a same-sized placeholder until the row is activated. */
+ menu: ReactNode;
parseFiles: (ids: string[]) => void;
t: any;
}
@@ -71,21 +70,12 @@ const FileListItemActions = ({
isFolder,
isPage,
isSupportedForChunking,
- menuItems,
+ menu,
parseFiles,
t,
}: FileListItemActionsProps) => {
const { allowed: canEditResources } = usePermission('edit_own_content');
const chunkTargetId = getChunkTargetId({ fileId, id });
- const transferMenuItems = useFileTransferMenuItem(
- id,
- isPage ? 'document' : isFolder ? 'folder' : 'file',
- );
-
- const mergedMenuItems = useMemo(() => {
- const baseItems = typeof menuItems === 'function' ? menuItems() : menuItems;
- return appendTransferMenuItemsBeforeDelete(baseItems, transferMenuItems);
- }, [menuItems, transferMenuItems]);
return (
<Flexbox
@@ -137,7 +127,7 @@ const FileListItemActions = ({
/>
</div>
))}
- <DropdownMenu className={styles.hover} items={mergedMenuItems} />
+ {menu}
</Flexbox>
);
};
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemMenu.test.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemMenu.test.tsx
new file mode 100644
index 00000000000..f1a2ee09f46
--- /dev/null
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemMenu.test.tsx
@@ -0,0 +1,85 @@
+import type { ItemType } from '@lobehub/ui';
+import { render, screen } from '@testing-library/react';
+import { createRef } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { FileListItemMenuGetter } from './FileListItemMenu';
+import FileListItemMenu from './FileListItemMenu';
+
+const mocks = vi.hoisted(() => ({
+ dropdownItems: vi.fn(),
+ menuItems: vi.fn(),
+ useFileTransferMenuItem: vi.fn(),
+}));
+
+vi.mock('@/business/client/hooks/useFileTransferMenuItem', () => ({
+ useFileTransferMenuItem: mocks.useFileTransferMenuItem,
+}));
+
+vi.mock('../../ItemDropdown/useFileItemDropdown', () => ({
+ useFileItemDropdown: () => ({ menuItems: mocks.menuItems }),
+}));
+
+vi.mock('../../ItemDropdown/DropdownMenu', () => ({
+ default: ({ items }: { items: unknown }) => {
+ mocks.dropdownItems(items);
+ return <button type="button">menu-trigger</button>;
+ },
+}));
+
+const baseProps = {
+ fileType: 'text/plain',
+ filename: 'Report.txt',
+ id: 'resource-1',
+ isFolder: false,
+ isPage: false,
+ size: 1024,
+ url: '',
+};
+
+describe('FileListItemMenu', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.menuItems.mockReturnValue([{ key: 'download' }, { key: 'delete' }] as ItemType[]);
+ mocks.useFileTransferMenuItem.mockReturnValue([{ key: 'transfer' }] as ItemType[]);
+ });
+
+ it('passes document entity type for page resources', () => {
+ const menuItemsRef = createRef<FileListItemMenuGetter | null>();
+
+ render(<FileListItemMenu {...baseProps} isPage menuItemsRef={menuItemsRef} />);
+
+ expect(mocks.useFileTransferMenuItem).toHaveBeenCalledWith('resource-1', 'document');
+ });
+
+ it('builds the dropdown items lazily, with transfer actions before delete', () => {
+ const menuItemsRef = createRef<FileListItemMenuGetter | null>();
+
+ render(<FileListItemMenu {...baseProps} menuItemsRef={menuItemsRef} />);
+
+ // Nothing is resolved until a menu actually opens.
+ expect(mocks.menuItems).not.toHaveBeenCalled();
+ const dropdownItems = mocks.dropdownItems.mock.lastCall?.[0] as () => ItemType[];
+ expect(dropdownItems).toBeTypeOf('function');
+
+ const keys = dropdownItems().map((item) => item && 'key' in item && item.key);
+ expect(keys).toEqual(['download', 'transfer', 'delete']);
+ });
+
+ it('gives the row context menu the base actions, as before', () => {
+ const menuItemsRef = createRef<FileListItemMenuGetter | null>();
+
+ render(<FileListItemMenu {...baseProps} menuItemsRef={menuItemsRef} />);
+
+ const keys = menuItemsRef.current!().map((item) => item && 'key' in item && item.key);
+ expect(keys).toEqual(['download', 'delete']);
+ });
+
+ it('moves focus to the real trigger when activated from the keyboard', () => {
+ const menuItemsRef = createRef<FileListItemMenuGetter | null>();
+
+ render(<FileListItemMenu {...baseProps} focusOnMount menuItemsRef={menuItemsRef} />);
+
+ expect(screen.getByRole('button', { name: 'menu-trigger' })).toHaveFocus();
+ });
+});
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemMenu.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemMenu.tsx
new file mode 100644
index 00000000000..70ce6c6e67c
--- /dev/null
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemMenu.tsx
@@ -0,0 +1,116 @@
+import type { ItemType } from '@lobehub/ui';
+import type { RefObject } from 'react';
+import { memo, useCallback, useLayoutEffect, useRef } from 'react';
+
+import { useFileTransferMenuItem } from '@/business/client/hooks/useFileTransferMenuItem';
+
+import DropdownMenu from '../../ItemDropdown/DropdownMenu';
+import { useFileItemDropdown } from '../../ItemDropdown/useFileItemDropdown';
+import { appendTransferMenuItemsBeforeDelete } from './FileListItemActions';
+
+export type FileListItemMenuGetter = () => ItemType[];
+
+type FileItemDropdownParams = Parameters<typeof useFileItemDropdown>[0];
+
+interface FileListItemMenuProps extends Pick<
+ FileItemDropdownParams,
+ | 'fileId'
+ | 'fileType'
+ | 'filename'
+ | 'id'
+ | 'libraryId'
+ | 'onRenameStart'
+ | 'size'
+ | 'sourceType'
+ | 'url'
+ | 'userId'
+ | 'visibility'
+> {
+ className?: string;
+ /** Move focus to the menu trigger once mounted (activated from the keyboard). */
+ focusOnMount?: boolean;
+ isFolder: boolean;
+ isPage: boolean;
+ /** Receives the base item getter for the row's right-click menu. */
+ menuItemsRef: RefObject<FileListItemMenuGetter | null>;
+ /** Open the menu on mount (the placeholder trigger was clicked or activated). */
+ openOnMount?: boolean;
+}
+
+/**
+ * The row's "…" dropdown and the source of its context menu items.
+ *
+ * Mounted only once a row is hovered or focused: every hook here (store
+ * selectors, the messenger SWR queries, the transfer targets) and the Base UI
+ * menu tree behind `DropdownMenu` used to run for each of the ~60 rows Virtuoso
+ * keeps mounted, so scrolling paid for dozens of closed menus per frame.
+ */
+const FileListItemMenu = memo<FileListItemMenuProps>(
+ ({
+ className,
+ fileId,
+ focusOnMount,
+ openOnMount,
+ fileType,
+ filename,
+ id,
+ isFolder,
+ isPage,
+ libraryId,
+ menuItemsRef,
+ onRenameStart,
+ size,
+ sourceType,
+ url,
+ userId,
+ visibility,
+ }) => {
+ const { menuItems } = useFileItemDropdown({
+ fileId,
+ fileType,
+ filename,
+ id,
+ libraryId,
+ onRenameStart,
+ size,
+ sourceType,
+ url,
+ userId,
+ visibility,
+ });
+ const transferMenuItems = useFileTransferMenuItem(
+ id,
+ isPage ? 'document' : isFolder ? 'folder' : 'file',
+ );
+
+ // Resolved only when a menu actually opens.
+ const getMenuItems = useCallback(
+ () => appendTransferMenuItemsBeforeDelete(menuItems(), transferMenuItems),
+ [menuItems, transferMenuItems],
+ );
+
+ // The right-click menu keeps its previous contents: the base actions only.
+ useLayoutEffect(() => {
+ menuItemsRef.current = menuItems;
+ }, [menuItems, menuItemsRef]);
+
+ const wrapperRef = useRef<HTMLSpanElement>(null);
+ // Read once: only the mount that replaces a focused placeholder moves focus.
+ const focusOnMountRef = useRef(focusOnMount);
+
+ useLayoutEffect(() => {
+ if (!focusOnMountRef.current) return;
+ wrapperRef.current?.querySelector<HTMLElement>('button, [tabindex]')?.focus();
+ }, []);
+
+ return (
+ <span ref={wrapperRef} style={{ display: 'contents' }}>
+ <DropdownMenu className={className} defaultOpen={openOnMount} items={getMenuItems} />
+ </span>
+ );
+ },
+);
+
+FileListItemMenu.displayName = 'FileListItemMenu';
+
+export default FileListItemMenu;
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/TruncatedFileName.test.ts b/src/features/ResourceManager/components/Explorer/ListView/ListItem/TruncatedFileName.test.ts
new file mode 100644
index 00000000000..fd218c8ac7e
--- /dev/null
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/TruncatedFileName.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from 'vitest';
+
+import { type MeasureRange, truncateFileNameToWidth } from './TruncatedFileName';
+
+/** Every character is 10px wide. */
+const monospace = (name: string): MeasureRange => {
+ void name;
+ return (start, end) => Math.max(0, end - start) * 10;
+};
+
+describe('truncateFileNameToWidth', () => {
+ it('keeps a name that fits', () => {
+ const name = 'report.pdf';
+
+ expect(truncateFileNameToWidth(name, 100, monospace(name), 30)).toBe(name);
+ });
+
+ it('truncates from the middle and keeps the extension', () => {
+ const name = 'quarterly-report-final.pdf';
+
+ // 160px: 30px ellipsis + 40px ".pdf" leaves 90px, i.e. 9 base characters
+ const result = truncateFileNameToWidth(name, 160, monospace(name), 30);
+
+ expect(result).toBe('quart...inal.pdf');
+ expect(result.length * 10).toBeLessThanOrEqual(160);
+ });
+
+ it('falls back to the ellipsis and extension when the base cannot fit', () => {
+ const name = 'quarterly-report-final.pdf';
+
+ expect(truncateFileNameToWidth(name, 70, monospace(name), 30)).toBe('....pdf');
+ });
+
+ it('treats a leading dot as part of the name', () => {
+ const name = '.environment-settings';
+
+ expect(truncateFileNameToWidth(name, 100, monospace(name), 30)).toBe('.env...ngs');
+ });
+
+ it('measures with the real glyph widths it is given', () => {
+ const name = '一个比较长的文件名.md';
+ // CJK glyphs are 20px, ASCII 10px
+ const widths = [...name].map((char) => (char.charCodeAt(0) > 0xff ? 20 : 10));
+ const measure: MeasureRange = (start, end) =>
+ widths.slice(start, end).reduce((sum, width) => sum + width, 0);
+
+ const result = truncateFileNameToWidth(name, 150, measure, 30);
+
+ expect(result).toBe('一个...件名.md');
+ const resultWidth = [...result].reduce(
+ (sum, char) => sum + (char.charCodeAt(0) > 0xff ? 20 : 10),
+ 0,
+ );
+ expect(resultWidth).toBeLessThanOrEqual(150);
+ });
+});
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/TruncatedFileName.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListItem/TruncatedFileName.tsx
index d112f01cf28..6c95d9c2b24 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/TruncatedFileName.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/TruncatedFileName.tsx
@@ -1,122 +1,237 @@
-import { memo, useEffect, useRef, useState } from 'react';
+import { memo, useEffect, useLayoutEffect, useRef, useState } from 'react';
interface TruncatedFileNameProps {
className?: string;
name: string;
}
+const ELLIPSIS = '...';
+/** Upper bound for the overflow correction below, in pixels. */
+const MAX_OVERFLOW_CORRECTION = 24;
+
+/** Rendered width of `name.slice(start, end)`. */
+export type MeasureRange = (start: number, end: number) => number;
+
+/**
+ * Middle-truncate `name` so it fits `maxWidth`, keeping the extension (the
+ * macOS Finder behaviour).
+ */
+export const truncateFileNameToWidth = (
+ name: string,
+ maxWidth: number,
+ measureRange: MeasureRange,
+ ellipsisWidth: number,
+): string => {
+ if (measureRange(0, name.length) <= maxWidth) return name;
+
+ // Only treat it as an extension when the dot is not leading and has content after it
+ const lastDotIndex = name.lastIndexOf('.');
+ const baseEnd = lastDotIndex > 0 && lastDotIndex < name.length - 1 ? lastDotIndex : name.length;
+ const extension = name.slice(baseEnd);
+
+ const availableWidth = maxWidth - ellipsisWidth - measureRange(baseEnd, name.length);
+ if (availableWidth <= 0) return `${ELLIPSIS}${extension}`;
+
+ const split = (length: number) => [Math.ceil(length / 2), Math.floor(length / 2)] as const;
+ const widthOf = (length: number) => {
+ const [headChars, tailChars] = split(length);
+ return measureRange(0, headChars) + measureRange(baseEnd - tailChars, baseEnd);
+ };
+
+ // Binary search the longest head + tail that still fits
+ let left = 0;
+ let right = baseEnd;
+ let best = 0;
+
+ while (left <= right) {
+ const mid = Math.floor((left + right) / 2);
+
+ if (widthOf(mid) <= availableWidth) {
+ best = mid;
+ left = mid + 1;
+ } else {
+ right = mid - 1;
+ }
+ }
+
+ if (best === 0) return `${ELLIPSIS}${extension}`;
+
+ const [headChars, tailChars] = split(best);
+ return `${name.slice(0, headChars)}${ELLIPSIS}${name.slice(baseEnd - tailChars, baseEnd)}${extension}`;
+};
+
+interface CharacterMetrics {
+ /** Rendered width of the full name. */
+ fullWidth: number;
+ measureRange: MeasureRange;
+ name: string;
+}
+
+/**
+ * Widths of segments of the rendered full name, read on demand through a Range
+ * and memoized for one measurement pass: the binary search only touches
+ * ~2·log₂(n) segments. Reads only, no DOM writes, so measuring every row a
+ * commit mounts costs a single layout.
+ *
+ * A segment's width is the larger of two readings: the distance between its
+ * first and last character edges (exact for left-to-right text, where it keeps
+ * the spacing a standalone segment box drops) and the segment's own bounding
+ * box (correct for right-to-left and mixed-direction names, whose edges can
+ * invert). Erring wide only ever truncates a little more, never overflows.
+ */
+const createCharacterMetrics = (node: Text, name: string, fullWidth: number) => {
+ const range = document.createRange();
+ const edges = new Map<number, DOMRect>();
+ const widths = new Map<string, number>();
+
+ const rectOf = (start: number, end: number) => {
+ range.setStart(node, start);
+ range.setEnd(node, end);
+ return range.getBoundingClientRect();
+ };
+
+ const charRect = (index: number) => {
+ let rect = edges.get(index);
+ if (!rect) {
+ rect = rectOf(index, index + 1);
+ edges.set(index, rect);
+ }
+ return rect;
+ };
+
+ const measureRange: MeasureRange = (start, end) => {
+ if (end <= start) return 0;
+ if (start === 0 && end === name.length) return fullWidth;
+
+ const key = `${start}:${end}`;
+ let width = widths.get(key);
+ if (width === undefined) {
+ const edgeWidth = charRect(end - 1).right - charRect(start).left;
+ width = Math.max(edgeWidth, rectOf(start, end).width);
+ widths.set(key, width);
+ }
+ return width;
+ };
+
+ return { fullWidth, measureRange, name } satisfies CharacterMetrics;
+};
+
+let measureContext: CanvasRenderingContext2D | null | undefined;
+
+/**
+ * Width of the ellipsis for a name without a period to measure. Periods come
+ * from the primary Latin font, which canvas renders like the DOM (the CJK
+ * fallback and tabular-number features that make canvas unreliable for whole
+ * names do not touch them).
+ */
+const measureEllipsis = (element: Element) => {
+ if (measureContext === undefined) {
+ measureContext = document.createElement('canvas').getContext('2d');
+ }
+ if (!measureContext) return 0;
+
+ const style = window.getComputedStyle(element);
+ measureContext.font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;
+ return measureContext.measureText(ELLIPSIS).width;
+};
+
+const truncateWithMetrics = (
+ { fullWidth, measureRange, name }: CharacterMetrics,
+ width: number,
+ element: Element,
+) => {
+ if (fullWidth <= width) return name;
+
+ // The extension dot gives the rendered width of "." directly.
+ const dotIndex = name.lastIndexOf('.');
+ const dotWidth = dotIndex >= 0 ? measureRange(dotIndex, dotIndex + 1) : 0;
+ const ellipsisWidth = dotWidth > 0 ? dotWidth * ELLIPSIS.length : measureEllipsis(element);
+
+ return truncateFileNameToWidth(name, width, measureRange, ellipsisWidth);
+};
+
/**
* Truncates file name from the center, preserving the extension at the end
* Similar to macOS Finder behavior
+ *
+ * Measurement is read-only and happens in one layout effect while the full
+ * name is rendered: its scroll width first, then only the character edges the
+ * binary search needs, through a Range. A commit that mounts many rows
+ * therefore lays the page out once. A real width change renders the full name
+ * again and re-measures, so edges are never read from an already-truncated
+ * text node. The previous version probed widths with a temporary span appended
+ * to `body`, forcing a synchronous reflow per probe — a dozen per row mount —
+ * which stalled every scroll step that mounted new rows.
*/
const TruncatedFileName = memo<TruncatedFileNameProps>(({ name, className }) => {
const containerRef = useRef<HTMLSpanElement>(null);
- const [displayName, setDisplayName] = useState(name);
-
- useEffect(() => {
+ const measuredWidthRef = useRef<number | null>(null);
+ // Pixels held back after a truncated result still overflowed; joining scripts
+ // (Arabic) reshape glyphs where a word is split, so segment widths can run a
+ // little short of the joined text.
+ const overflowCorrectionRef = useRef({ name, px: 0 });
+ // Bumped on a width change so the full name renders and is measured again.
+ const [measureEpoch, setMeasureEpoch] = useState(0);
+ const [truncated, setTruncated] = useState<{
+ epoch: number;
+ name: string;
+ text: string;
+ } | null>(null);
+
+ // Until this name is measured at the current width, render it in full.
+ const displayName =
+ truncated?.name === name && truncated.epoch === measureEpoch ? truncated.text : name;
+
+ useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
- const updateTruncation = () => {
- const containerWidth = container.offsetWidth;
- if (containerWidth === 0) return;
-
- // Create a temporary span to measure text width
- const measureSpan = document.createElement('span');
- measureSpan.style.visibility = 'hidden';
- measureSpan.style.position = 'absolute';
- measureSpan.style.whiteSpace = 'nowrap';
- measureSpan.style.font = window.getComputedStyle(container).font;
- document.body.append(measureSpan);
-
- // Measure full name
- measureSpan.textContent = name;
- const fullWidth = measureSpan.offsetWidth;
-
- // If it fits, show the full name
- if (fullWidth <= containerWidth) {
- setDisplayName(name);
- measureSpan.remove();
- return;
- }
-
- // Split filename and extension
- const lastDotIndex = name.lastIndexOf('.');
- let baseName = name;
- let extension = '';
-
- // Only treat as extension if dot is not at the start and there's content after it
- if (lastDotIndex > 0 && lastDotIndex < name.length - 1) {
- baseName = name.slice(0, lastDotIndex);
- extension = name.slice(lastDotIndex); // includes the dot
- }
-
- // Measure ellipsis width
- measureSpan.textContent = '...';
- const ellipsisWidth = measureSpan.offsetWidth;
-
- // Measure extension width
- measureSpan.textContent = extension;
- const extensionWidth = measureSpan.offsetWidth;
-
- // Calculate available width for base name
- const availableWidth = containerWidth - ellipsisWidth - extensionWidth;
-
- if (availableWidth <= 0) {
- // Not enough space, just show ellipsis + extension
- setDisplayName(`...${extension}`);
- measureSpan.remove();
- return;
- }
-
- // Binary search to find the optimal split point
- let left = 0;
- let right = baseName.length;
- let bestFit = '';
-
- while (left <= right) {
- const mid = Math.floor((left + right) / 2);
- const startChars = Math.ceil(mid / 2);
- const endChars = Math.floor(mid / 2);
-
- const truncated =
- baseName.slice(0, startChars) + (mid > 0 ? baseName.slice(-endChars) : '');
-
- measureSpan.textContent = truncated;
- const truncatedWidth = measureSpan.offsetWidth;
-
- if (truncatedWidth <= availableWidth) {
- bestFit = truncated;
- left = mid + 1;
- } else {
- right = mid - 1;
- }
- }
-
- measureSpan.remove();
-
- // Construct final truncated name
- if (bestFit.length === 0) {
- setDisplayName(`...${extension}`);
- } else {
- const startChars = Math.ceil(bestFit.length / 2);
- const endChars = Math.floor(bestFit.length / 2);
- setDisplayName(
- `${baseName.slice(0, startChars)}...${baseName.slice(-endChars)}${extension}`,
- );
- }
- };
+ const node = container.firstChild;
+ if (!(node instanceof Text) || node.data !== name) return;
+
+ const width = container.clientWidth;
+ measuredWidthRef.current = width;
+ if (width <= 0) return;
- updateTruncation();
+ if (overflowCorrectionRef.current.name !== name)
+ overflowCorrectionRef.current = { name, px: 0 };
+ const metrics = createCharacterMetrics(node, name, container.scrollWidth);
+ const text = truncateWithMetrics(metrics, width - overflowCorrectionRef.current.px, container);
+ setTruncated({ epoch: measureEpoch, name, text });
+ }, [name, measureEpoch]);
- // Use ResizeObserver to handle container size changes
- const resizeObserver = new ResizeObserver(updateTruncation);
+ // A truncated result that still overflows is measured again with the excess
+ // held back. Reads only; rare in practice (joining scripts).
+ useLayoutEffect(() => {
+ const container = containerRef.current;
+ if (!container || displayName === name) return;
+
+ const overflow = container.scrollWidth - container.clientWidth;
+ const correction = overflowCorrectionRef.current;
+ if (overflow <= 0 || correction.name !== name) return;
+ if (correction.px >= MAX_OVERFLOW_CORRECTION) return;
+
+ correction.px += overflow + 1;
+ setMeasureEpoch((epoch) => epoch + 1);
+ }, [displayName, name]);
+
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!container || typeof ResizeObserver === 'undefined') return;
+
+ const resizeObserver = new ResizeObserver(([entry]) => {
+ const width = entry?.contentRect.width ?? 0;
+ const measured = measuredWidthRef.current;
+ // The initial observation and sub-pixel noise are not a resize.
+ if (measured !== null && Math.abs(width - measured) < 0.5) return;
+ setMeasureEpoch((epoch) => epoch + 1);
+ });
resizeObserver.observe(container);
return () => {
resizeObserver.disconnect();
};
- }, [name]);
+ }, []);
return (
<span className={className} ref={containerRef} title={name}>
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.test.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.test.tsx
index 5a48689bc41..c223ea1785e 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.test.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.test.tsx
@@ -1,4 +1,4 @@
-import { render, screen } from '@testing-library/react';
+import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import FileListItem from './index';
@@ -52,12 +52,18 @@ vi.mock('../../hooks/useFileItemClick', () => ({
useFileItemDoubleClick: () => vi.fn(),
}));
-vi.mock('../../ItemDropdown/useFileItemDropdown', () => ({
- useFileItemDropdown: () => ({ menuItems: [] }),
+vi.mock('./FileListItemMenu', () => ({
+ default: ({ focusOnMount, openOnMount }: { focusOnMount?: boolean; openOnMount?: boolean }) => (
+ <span
+ data-focus-on-mount={String(!!focusOnMount)}
+ data-open-on-mount={String(!!openOnMount)}
+ data-testid="row-menu"
+ />
+ ),
}));
vi.mock('./FileListItemActions', () => ({
- default: () => null,
+ default: ({ menu }: { menu: React.ReactNode }) => <>{menu}</>,
}));
vi.mock('./FileListItemName', () => ({
@@ -140,6 +146,49 @@ describe('FileListItem', () => {
expect(screen.getByTestId('avatar')).toHaveAttribute('data-fallback-variant', 'pixel');
});
+ // Regression: every row Virtuoso rendered mounted its own closed Base UI menu
+ // (plus the menu hooks), which made scrolling a long drive list stall.
+ it('mounts the row menu only once the row is hovered', () => {
+ render(<FileListItem {...baseProps} />);
+
+ expect(screen.queryByTestId('row-menu')).not.toBeInTheDocument();
+
+ fireEvent.pointerEnter(screen.getByText('Report.txt').closest('[data-row-index]')!);
+
+ expect(screen.getByTestId('row-menu')).toBeInTheDocument();
+ });
+
+ it('mounts the row menu when the row receives keyboard focus', () => {
+ render(<FileListItem {...baseProps} />);
+
+ fireEvent.focus(screen.getByRole('checkbox'));
+
+ expect(screen.getByTestId('row-menu')).toBeInTheDocument();
+ });
+
+ // Keyboard users must still reach the menu on rows without an enabled
+ // checkbox (other members' files, folders, pages).
+ it('keeps a focusable menu trigger before the row is activated', () => {
+ render(<FileListItem {...baseProps} selectable={false} />);
+
+ const trigger = screen.getByRole('button', { name: 'more' });
+ expect(screen.queryByTestId('row-menu')).not.toBeInTheDocument();
+
+ fireEvent.focus(trigger);
+
+ expect(screen.getByTestId('row-menu')).toHaveAttribute('data-focus-on-mount', 'true');
+ expect(screen.getByTestId('row-menu')).toHaveAttribute('data-open-on-mount', 'false');
+ });
+
+ // Assistive tech and programmatic clicks activate without focus/hover first.
+ it('opens the real menu when the placeholder trigger is clicked', () => {
+ render(<FileListItem {...baseProps} selectable={false} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'more' }));
+
+ expect(screen.getByTestId('row-menu')).toHaveAttribute('data-open-on-mount', 'true');
+ });
+
it('disables selection for rows the workspace member did not upload', () => {
render(<FileListItem {...baseProps} selectable={false} />);
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx
index 45185632de6..f42d4ab1b3c 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx
@@ -9,7 +9,7 @@ import {
Tooltip,
} from '@lobehub/ui';
import { isEqual } from 'es-toolkit';
-import { memo, useCallback } from 'react';
+import { memo, useCallback, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { shallow } from 'zustand/shallow';
@@ -22,9 +22,9 @@ import type { FileListItem as FileListItemType } from '@/types/files';
import { formatSize } from '@/utils/format';
import { useFileItemClick, useFileItemDoubleClick } from '../../hooks/useFileItemClick';
-import { useFileItemDropdown } from '../../ItemDropdown/useFileItemDropdown';
import { getListViewMinWidth } from './constants';
import FileListItemActions from './FileListItemActions';
+import FileListItemMenu, { type FileListItemMenuGetter } from './FileListItemMenu';
import FileListItemName from './FileListItemName';
import { useFileListItemDrag } from './useFileListItemDrag';
import { useFileListItemMeta } from './useFileListItemMeta';
@@ -102,6 +102,18 @@ const styles = createStaticStyles(({ css }) => {
color: ${cssVar.colorText};
white-space: nowrap;
`,
+ menuPlaceholder: css`
+ cursor: pointer;
+
+ flex-shrink: 0;
+
+ width: 24px;
+ height: 24px;
+ padding: 0;
+ border: none;
+
+ background: transparent;
+ `,
nameContainer: css`
overflow: hidden;
flex: 1;
@@ -168,7 +180,7 @@ const FileListItem = ({
userId,
visibility,
}: FileListItemProps) => {
- const { t } = useTranslation(['components', 'file', 'chat']);
+ const { t } = useTranslation(['components', 'file', 'chat', 'common']);
const uploaderName =
uploader?.fullName || uploader?.username || (uploader?.id ? uploader.id.slice(0, 8) : '');
const chunkTargetId = getChunkTargetId({ fileId, id });
@@ -255,19 +267,52 @@ const FileListItem = ({
isPage,
libraryId: resourceManagerState.libraryId,
});
- const { menuItems } = useFileItemDropdown({
- fileId,
- fileType,
- filename: name,
- id,
- libraryId: resourceManagerState.libraryId,
- onRenameStart: isFolder ? handleRenameStart : undefined,
- size,
- sourceType,
- url,
- userId,
- visibility,
- });
+
+ // The row menu (its hooks plus a Base UI menu tree) mounts on first hover or
+ // focus instead of for every row Virtuoso renders; scrolling a long list used
+ // to mount and tear down dozens of closed menus per frame.
+ const [menuActivation, setMenuActivation] = useState<'click' | 'focus' | 'pointer' | null>(null);
+ const menuActivated = menuActivation !== null;
+ const activateMenu = useCallback(() => setMenuActivation((prev) => prev ?? 'pointer'), []);
+ // Keyboard users reach the placeholder trigger first; hand focus to the real
+ // trigger once it mounts so Tab/Enter keep working.
+ const activateMenuFromFocus = useCallback(() => setMenuActivation((prev) => prev ?? 'focus'), []);
+ // A click on the placeholder (assistive tech, programmatic `click()`) opens
+ // the real menu right away instead of only swapping the trigger in.
+ const activateMenuFromClick = useCallback(() => setMenuActivation((prev) => prev ?? 'click'), []);
+ const menuItemsRef = useRef<FileListItemMenuGetter | null>(null);
+ const getContextMenuItems = useCallback(() => menuItemsRef.current?.() ?? [], []);
+
+ const rowMenu = menuActivated ? (
+ <FileListItemMenu
+ className={styles.hover}
+ fileId={fileId}
+ fileType={fileType}
+ filename={name}
+ focusOnMount={menuActivation === 'focus' || menuActivation === 'click'}
+ id={id}
+ isFolder={isFolder}
+ isPage={isPage}
+ libraryId={resourceManagerState.libraryId}
+ menuItemsRef={menuItemsRef}
+ openOnMount={menuActivation === 'click'}
+ size={size}
+ sourceType={sourceType}
+ url={url}
+ userId={userId}
+ visibility={visibility}
+ onRenameStart={isFolder ? handleRenameStart : undefined}
+ />
+ ) : (
+ <button
+ aria-haspopup="menu"
+ aria-label={t('more', { ns: 'common' })}
+ className={cx(styles.menuPlaceholder, styles.hover)}
+ type="button"
+ onClick={activateMenuFromClick}
+ onFocus={activateMenuFromFocus}
+ />
+ );
const handleCheckboxClick = useCallback(
(e: React.MouseEvent) => {
@@ -286,7 +331,7 @@ const FileListItem = ({
}, []);
return (
- <ContextMenuTrigger items={menuItems}>
+ <ContextMenuTrigger items={menuActivated ? getContextMenuItems : undefined}>
<Flexbox
horizontal
align={'center'}
@@ -316,6 +361,8 @@ const FileListItem = ({
onDragOver={handleDragOver}
onDragStart={handleDragStart}
onDrop={handleDrop}
+ onFocus={menuActivated ? undefined : activateMenu}
+ onPointerEnter={menuActivated ? undefined : activateMenu}
>
<Center
height={40}
@@ -369,7 +416,7 @@ const FileListItem = ({
isFolder={isFolder}
isPage={isPage}
isSupportedForChunking={isSupportedForChunking}
- menuItems={menuItems}
+ menu={rowMenu}
parseFiles={fileStoreState.parseFiles}
t={t}
/>
diff --git a/src/features/ResourceManager/components/Explorer/ListView/VirtualizedFileList.tsx b/src/features/ResourceManager/components/Explorer/ListView/VirtualizedFileList.tsx
index c8af3dbfc64..0ff85106b76 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/VirtualizedFileList.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/VirtualizedFileList.tsx
@@ -1,6 +1,6 @@
import type { RefObject } from 'react';
-import { useCallback, useEffect, useRef } from 'react';
-import type { VirtuosoHandle } from 'react-virtuoso';
+import { useCallback, useEffect, useLayoutEffect, useRef } from 'react';
+import type { ListRange, VirtuosoHandle } from 'react-virtuoso';
import { Virtuoso } from 'react-virtuoso';
import { useResourceManagerStore } from '@/features/ResourceManager/store';
@@ -9,7 +9,35 @@ import type { FileListItem } from '@/types/files';
import { useExplorerSelectionActions } from '../hooks/useExplorerSelection';
import FileListItemComponent from './ListItem';
-import { useExplorerInfiniteScroll } from './useExplorerInfiniteScroll';
+import {
+ ExplorerListFooter,
+ type ExplorerListFooterContext,
+ useExplorerInfiniteScroll,
+} from './useExplorerInfiniteScroll';
+
+const LIST_COMPONENTS = { Footer: ExplorerListFooter };
+
+const ROW_HEIGHT = 48;
+
+/**
+ * Rows rendered beyond the viewport. The previous 2000px budget kept ~40
+ * off-screen interactive rows mounted, and every scroll step had to mount a
+ * matching batch, blocking the main thread long enough for a fling to outrun
+ * the rendered rows (a white list). Measured under 4x CPU throttling, a small
+ * margin keeps each step short; a deeper one (20 rows) made the blank frames
+ * worse, not better.
+ */
+const INCREASE_VIEWPORT_BY = { bottom: ROW_HEIGHT * 8, top: ROW_HEIGHT * 4 };
+
+/**
+ * Rows before the end at which the next page starts loading. Rendering margin
+ * and prefetch distance are separate on purpose: `endReached` alone only fires
+ * once the last row is rendered, which the small margin above would delay
+ * until the user is already at the bottom.
+ */
+const PREFETCH_ROWS = 20;
+
+const computeItemKey = (index: number, item: FileListItem | undefined) => item?.id ?? index;
interface VirtualizedFileListProps {
columnWidths: {
@@ -51,7 +79,7 @@ const VirtualizedFileList = ({
setSelectedFileIds,
toggleItemSelection,
} = useExplorerSelectionActions(data);
- const { Footer, handleEndReached } = useExplorerInfiniteScroll({
+ const { footerContext, handleEndReached, prefetchMore } = useExplorerInfiniteScroll({
columnWidths,
dataLength: data.length,
hasMore,
@@ -59,13 +87,38 @@ const VirtualizedFileList = ({
loadMoreError,
showUploader,
});
+ const dataLength = data.length;
+ const handleRangeChanged = useCallback(
+ ({ endIndex }: ListRange) => {
+ if (hasMore && endIndex >= dataLength - PREFETCH_ROWS) void prefetchMore();
+ },
+ [dataLength, hasMore, prefetchMore],
+ );
const dataRef = useRef<FileListItem[]>(data);
const lastSelectedIndexRef = useRef<number | null>(null);
+ // The selection helpers are rebuilt whenever `data` changes (every page
+ // load). Reading them through a ref keeps `handleSelectionChange` — a prop of
+ // every row — stable, so loading a page no longer re-renders each mounted row.
+ const selectionActionsRef = useRef({
+ clearSelectAllState,
+ isItemSelectable,
+ setSelectedFileIds,
+ toggleItemSelection,
+ });
useEffect(() => {
dataRef.current = data;
}, [data]);
+ useLayoutEffect(() => {
+ selectionActionsRef.current = {
+ clearSelectAllState,
+ isItemSelectable,
+ setSelectedFileIds,
+ toggleItemSelection,
+ };
+ });
+
useEffect(() => {
return useResourceManagerStore.subscribe(
(s) => s.selectedFileIds.length,
@@ -79,6 +132,9 @@ const VirtualizedFileList = ({
const handleSelectionChange = useCallback(
(id: string, checked: boolean, shiftKey: boolean, clickedIndex: number) => {
+ const { clearSelectAllState, isItemSelectable, setSelectedFileIds, toggleItemSelection } =
+ selectionActionsRef.current;
+
if (shiftKey && lastSelectedIndexRef.current !== null && dataRef.current.length > 0) {
clearSelectAllState();
@@ -102,18 +158,21 @@ const VirtualizedFileList = ({
lastSelectedIndexRef.current = clickedIndex;
},
- [clearSelectAllState, isItemSelectable, setSelectedFileIds, toggleItemSelection],
+ [],
);
return (
- <Virtuoso
- components={{ Footer }}
+ <Virtuoso<FileListItem, ExplorerListFooterContext>
+ components={LIST_COMPONENTS}
+ computeItemKey={computeItemKey}
+ context={footerContext}
data={data}
- defaultItemHeight={48}
+ defaultItemHeight={ROW_HEIGHT}
endReached={handleEndReached}
- increaseViewportBy={{ bottom: 800, top: 1200 }}
- initialItemCount={30}
- overscan={48 * 5}
+ fixedItemHeight={ROW_HEIGHT}
+ increaseViewportBy={INCREASE_VIEWPORT_BY}
+ initialItemCount={Math.min(30, data.length)}
+ rangeChanged={handleRangeChanged}
ref={virtuosoRef}
style={{ height }}
itemContent={useCallback(
@@ -126,7 +185,6 @@ const VirtualizedFileList = ({
<FileListItemComponent
columnWidths={columnWidths}
index={index}
- key={item.id}
selectable={selectable}
showUploader={showUploader}
selected={
diff --git a/src/features/ResourceManager/components/Explorer/ListView/useExplorerInfiniteScroll.test.tsx b/src/features/ResourceManager/components/Explorer/ListView/useExplorerInfiniteScroll.test.tsx
index 938ba4c3b54..e6d68a1a0b7 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/useExplorerInfiniteScroll.test.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/useExplorerInfiniteScroll.test.tsx
@@ -46,4 +46,105 @@ describe('useExplorerInfiniteScroll', () => {
expect(loadMore).toHaveBeenCalledTimes(1);
});
+
+ // Regression: Virtuoso fires `endReached` for the new last row while the
+ // previous page is still settling. The old state-based guard dropped that
+ // call, and Virtuoso never repeats it for the same row, so a fast scroll got
+ // stuck at the bottom with more pages unloaded.
+ it('should load again when the end is reached while a page is in flight', async () => {
+ let resolvePage!: () => void;
+ const loadMore = vi
+ .fn()
+ .mockImplementationOnce(() => new Promise<void>((resolve) => (resolvePage = resolve)))
+ .mockResolvedValue(undefined);
+ const { result } = renderHook(() =>
+ useExplorerInfiniteScroll({ columnWidths, dataLength: 50, hasMore: true, loadMore }),
+ );
+
+ let first!: Promise<void>;
+ act(() => {
+ first = result.current.handleEndReached();
+ });
+ await act(() => result.current.handleEndReached());
+ expect(loadMore).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ resolvePage();
+ await first;
+ });
+
+ expect(loadMore).toHaveBeenCalledTimes(2);
+ expect(result.current.footerContext.isLoadingMore).toBe(false);
+ });
+
+ // Regression: a page that failed while the end was reached again must stop
+ // at the Retry footer instead of retrying on its own.
+ it('should not run a queued load after the page in flight failed', async () => {
+ let resolvePage!: () => void;
+ const loadMore = vi
+ .fn()
+ .mockImplementationOnce(() => new Promise<void>((resolve) => (resolvePage = resolve)))
+ .mockResolvedValue(undefined);
+ const { result, rerender } = renderHook(
+ ({ loadMoreError }: { loadMoreError?: unknown }) =>
+ useExplorerInfiniteScroll({
+ columnWidths,
+ dataLength: 50,
+ hasMore: true,
+ loadMore,
+ loadMoreError,
+ }),
+ { initialProps: {} as { loadMoreError?: unknown } },
+ );
+
+ let first!: Promise<void>;
+ act(() => {
+ first = result.current.handleEndReached();
+ });
+ await act(() => result.current.handleEndReached());
+
+ // The pager records the failure and resolves the request.
+ await act(async () => {
+ rerender({ loadMoreError: failedPage });
+ resolvePage();
+ await first;
+ });
+
+ expect(loadMore).toHaveBeenCalledTimes(1);
+ });
+
+ it('should not queue a prefetch behind a page in flight', async () => {
+ let resolvePage!: () => void;
+ const loadMore = vi
+ .fn()
+ .mockImplementationOnce(() => new Promise<void>((resolve) => (resolvePage = resolve)))
+ .mockResolvedValue(undefined);
+ const { result } = renderHook(() =>
+ useExplorerInfiniteScroll({ columnWidths, dataLength: 50, hasMore: true, loadMore }),
+ );
+
+ let first!: Promise<void>;
+ act(() => {
+ first = result.current.prefetchMore();
+ });
+ await act(() => result.current.prefetchMore());
+
+ await act(async () => {
+ resolvePage();
+ await first;
+ });
+
+ expect(loadMore).toHaveBeenCalledTimes(1);
+ });
+
+ it('should not load when there are no more pages', async () => {
+ const loadMore = vi.fn().mockResolvedValue(undefined);
+ const { result } = renderHook(() =>
+ useExplorerInfiniteScroll({ columnWidths, dataLength: 50, hasMore: false, loadMore }),
+ );
+
+ await act(() => result.current.handleEndReached());
+
+ expect(loadMore).not.toHaveBeenCalled();
+ });
});
diff --git a/src/features/ResourceManager/components/Explorer/ListView/useExplorerInfiniteScroll.tsx b/src/features/ResourceManager/components/Explorer/ListView/useExplorerInfiniteScroll.tsx
index 339b8721054..a47f182a7f7 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/useExplorerInfiniteScroll.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/useExplorerInfiniteScroll.tsx
@@ -1,17 +1,19 @@
-import { useCallback, useState } from 'react';
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import AsyncError from '@/components/AsyncError';
import { useFileStore } from '@/store/file';
import ListViewSkeleton from './Skeleton';
+interface ColumnWidths {
+ date: number;
+ name: number;
+ size: number;
+ uploader: number;
+}
+
interface UseExplorerInfiniteScrollOptions {
- columnWidths: {
- date: number;
- name: number;
- size: number;
- uploader: number;
- };
+ columnWidths: ColumnWidths;
dataLength: number;
hasMore: boolean;
/** Next-page loader; defaults to the folder list's. */
@@ -25,6 +27,51 @@ interface UseExplorerInfiniteScrollOptions {
showUploader?: boolean;
}
+/** What the list footer renders from; handed to Virtuoso as its `context`. */
+export interface ExplorerListFooterContext {
+ columnWidths: ColumnWidths;
+ dataLength: number;
+ hasMore: boolean;
+ isLoadingMore: boolean;
+ loadMoreError?: unknown;
+ retryLoadMore: () => Promise<void>;
+ showUploader: boolean;
+}
+
+/**
+ * Module-level so its identity never changes: Virtuoso remounts a footer whose
+ * component type changes, and a footer rebuilt on every page load made the
+ * list height jump while scrolling. The state arrives through `context`.
+ */
+export const ExplorerListFooter = ({ context }: { context?: ExplorerListFooterContext }) => {
+ if (!context) return null;
+
+ const {
+ columnWidths,
+ dataLength,
+ hasMore,
+ isLoadingMore,
+ loadMoreError,
+ retryLoadMore,
+ showUploader,
+ } = context;
+
+ if (loadMoreError)
+ return (
+ <AsyncError
+ error={loadMoreError}
+ retrying={isLoadingMore}
+ variant={'inline'}
+ onRetry={retryLoadMore}
+ />
+ );
+ if (isLoadingMore && hasMore)
+ return <ListViewSkeleton columnWidths={columnWidths} showUploader={showUploader} />;
+ if (hasMore === false && dataLength > 0) return <div aria-hidden style={{ height: 96 }} />;
+
+ return null;
+};
+
export const useExplorerInfiniteScroll = ({
columnWidths,
dataLength,
@@ -37,19 +84,60 @@ export const useExplorerInfiniteScroll = ({
const loadNextPage = loadMore ?? loadMoreResources;
const [isLoadingMore, setIsLoadingMore] = useState(false);
- // The loader itself, without the guards: a manual retry has to run while the
- // recorded error is still set — the replica only clears it when the request
- // starts, so guarding on it here would make the Retry action a no-op.
- const runLoadMore = useCallback(async () => {
- if (!hasMore || isLoadingMore) return;
+ // The in-flight guard lives in a ref, not in render state: Virtuoso fires
+ // `endReached` for the new last row as soon as a page lands, which is before
+ // the `isLoadingMore` state from that load has been cleared. A state guard
+ // dropped that call, and since Virtuoso does not repeat `endReached` for the
+ // same row, a fast scroll stopped at the bottom with more pages unloaded.
+ const inFlightRef = useRef(false);
+ const reachedEndWhileLoadingRef = useRef(false);
+ const latestRef = useRef({ hasMore, loadMoreError, loadNextPage });
+ // Bumped when the end was reached mid-load; the follow-up load runs from an
+ // effect, after the finished page (or its error) has been rendered.
+ const [queuedLoad, setQueuedLoad] = useState(0);
+
+ useLayoutEffect(() => {
+ latestRef.current = { hasMore, loadMoreError, loadNextPage };
+ });
+ // The loader itself, without the error guard: a manual retry has to run while
+ // the recorded error is still set — the replica only clears it when the
+ // request starts, so guarding on it here would make the Retry action a no-op.
+ // `queueIfBusy`: remember a request that arrives mid-load and run it after the
+ // current page lands. Only the real end of the list queues; a prefetch hint
+ // that arrives mid-load is already served by the page in flight.
+ const runLoadMore = useCallback(async (queueIfBusy = true) => {
+ if (inFlightRef.current) {
+ if (queueIfBusy) reachedEndWhileLoadingRef.current = true;
+ return;
+ }
+
+ inFlightRef.current = true;
setIsLoadingMore(true);
+ reachedEndWhileLoadingRef.current = false;
try {
- await loadNextPage();
+ if (latestRef.current.hasMore) await latestRef.current.loadNextPage();
} finally {
+ inFlightRef.current = false;
setIsLoadingMore(false);
+ if (reachedEndWhileLoadingRef.current) {
+ reachedEndWhileLoadingRef.current = false;
+ setQueuedLoad((count) => count + 1);
+ }
}
- }, [hasMore, isLoadingMore, loadNextPage]);
+ }, []);
+
+ // Runs the queued load against the rendered outcome of the previous page: a
+ // page that failed stops here (the footer's Retry takes over), and so does
+ // the last page.
+ useEffect(() => {
+ if (queuedLoad === 0) return;
+
+ const { hasMore: canLoadMore, loadMoreError: pageError } = latestRef.current;
+ if (pageError || !canLoadMore) return;
+
+ void runLoadMore();
+ }, [queuedLoad, runLoadMore]);
const handleEndReached = useCallback(async () => {
// Auto-loading stops on a failed page so scrolling cannot hammer it; the
@@ -59,28 +147,32 @@ export const useExplorerInfiniteScroll = ({
await runLoadMore();
}, [loadMoreError, runLoadMore]);
+ /** Load the next page ahead of the end; never queues behind a page in flight. */
+ const prefetchMore = useCallback(async () => {
+ if (loadMoreError) return;
+
+ await runLoadMore(false);
+ }, [loadMoreError, runLoadMore]);
+
const retryLoadMore = useCallback(() => runLoadMore(), [runLoadMore]);
- const Footer = useCallback(() => {
- if (loadMoreError)
- return (
- <AsyncError
- error={loadMoreError}
- retrying={isLoadingMore}
- variant={'inline'}
- onRetry={retryLoadMore}
- />
- );
- if (isLoadingMore && hasMore)
- return <ListViewSkeleton columnWidths={columnWidths} showUploader={showUploader} />;
- if (hasMore === false && dataLength > 0) return <div aria-hidden style={{ height: 96 }} />;
-
- return null;
- }, [columnWidths, dataLength, hasMore, isLoadingMore, loadMoreError, retryLoadMore, showUploader]);
+ const footerContext = useMemo<ExplorerListFooterContext>(
+ () => ({
+ columnWidths,
+ dataLength,
+ hasMore,
+ isLoadingMore,
+ loadMoreError,
+ retryLoadMore,
+ showUploader,
+ }),
+ [columnWidths, dataLength, hasMore, isLoadingMore, loadMoreError, retryLoadMore, showUploader],
+ );
return {
- Footer,
+ footerContext,
handleEndReached,
+ prefetchMore,
retryLoadMore,
};
};