Fix search card virtualization and result count

This commit is contained in:
ShiGuangAlex
2026-04-11 17:06:33 +08:00
parent 7ba91a0293
commit e92e49f04f
2 changed files with 273 additions and 103 deletions
+74 -39
View File
@@ -355,19 +355,21 @@ function SearchPageClient() {
return normalizedTitle.includes(normalizedQuery);
};
const allExactSearchResults = useMemo(() => {
if (!exactSearch) return searchResults;
return searchResults.filter((item) =>
titleContainsQuery(item.title, currentQueryRef.current)
);
}, [searchResults, searchQuery, exactSearch]);
// 聚合后的结果(按标题和年份分组)
const aggregatedResults = useMemo(() => {
// 首先应用精确搜索过滤
const filteredResults = exactSearch
? searchResults.filter((item) =>
titleContainsQuery(item.title, currentQueryRef.current)
)
: searchResults;
//===== 阶段1:按 normalizedTitle-type 初步分组 =====
const preliminaryMap = new Map<string, SearchResult[]>();
filteredResults.forEach((item) => {
allExactSearchResults.forEach((item) => {
const normalizedTitle = normalizeTitle(item.title);
const type = getType(item);
const preliminaryKey = `${normalizedTitle}-${type}`;
@@ -428,7 +430,7 @@ function SearchPageClient() {
return keyOrder.map(
(key) => [key, finalMap.get(key)!] as [string, SearchResult[]]
);
}, [searchResults, exactSearch]);
}, [allExactSearchResults]);
// 当聚合结果变化时,如果某个聚合已存在,则调用其卡片 ref 的 set 方法增量更新
useEffect(() => {
@@ -641,14 +643,7 @@ function SearchPageClient() {
const filteredAllResults = useMemo(() => {
const { source, title, year, yearOrder } = filterAll;
// 首先应用精确搜索过滤
const exactSearchFiltered = exactSearch
? searchResults.filter((item) =>
titleContainsQuery(item.title, currentQueryRef.current)
)
: searchResults;
const filtered = exactSearchFiltered.filter((item) => {
const filtered = allExactSearchResults.filter((item) => {
if (source !== 'all' && item.source !== source) return false;
if (title !== 'all' && item.title !== title) return false;
if (year !== 'all' && item.year !== year) return false;
@@ -677,7 +672,7 @@ function SearchPageClient() {
? a.title.localeCompare(b.title)
: b.title.localeCompare(a.title);
});
}, [searchResults, filterAll, searchQuery, exactSearch]);
}, [allExactSearchResults, filterAll, searchQuery]);
// 聚合:应用筛选与排序
const filteredAggResults = useMemo(() => {
@@ -734,6 +729,30 @@ function SearchPageClient() {
filteredAllResults.length,
]);
const resultCountMeta = useMemo(() => {
const isAggregateView = viewMode === 'agg';
const visibleCount = isAggregateView
? filteredAggResults.length
: filteredAllResults.length;
const totalCount = isAggregateView
? aggregatedResults.length
: allExactSearchResults.length;
return {
visibleCount,
totalCount,
isFiltered: visibleCount !== totalCount,
modeLabel: isAggregateView ? '聚合结果' : '搜索结果',
unit: isAggregateView ? '组' : '条',
};
}, [
viewMode,
filteredAggResults.length,
filteredAllResults.length,
aggregatedResults.length,
allExactSearchResults.length,
]);
useEffect(() => {
if (typeof window !== 'undefined') {
localStorage.setItem('searchResultDisplayMode', resultDisplayMode);
@@ -1570,28 +1589,44 @@ function SearchPageClient() {
<>
{/* 影视搜索结果 */}
{/* 标题 */}
<div className='mb-4 flex items-center justify-between'>
<h2 className='text-xl font-bold text-gray-800 dark:text-gray-200'>
{isFromCache ? (
<span className='ml-2 rounded-md bg-green-50 px-2 py-0.5 text-xs font-medium text-green-600 dark:bg-green-900/30 dark:text-green-400'>
<div className='mb-4 flex items-start justify-between gap-4'>
<div className='min-w-0'>
<h2 className='text-xl font-bold text-gray-800 dark:text-gray-200'>
{isFromCache ? (
<span className='ml-2 rounded-md bg-green-50 px-2 py-0.5 text-xs font-medium text-green-600 dark:bg-green-900/30 dark:text-green-400'>
</span>
) : (
<>
{totalSources > 0 && useFluidSearch && (
<span className='ml-2 text-sm font-normal text-gray-500 dark:text-gray-400'>
{completedSources}/{totalSources}
</span>
)}
{isLoading && useFluidSearch && (
<span className='ml-2 inline-block align-middle'>
<span className='inline-block h-3 w-3 animate-spin rounded-full border-2 border-gray-300 border-t-green-500'></span>
</span>
)}
</>
)}
</h2>
<div className='mt-2 flex flex-wrap items-center gap-2 text-xs'>
<span className='inline-flex items-center rounded-full bg-gray-100 px-2.5 py-1 font-medium text-gray-700 dark:bg-gray-800 dark:text-gray-200'>
{resultCountMeta.modeLabel}{' '}
{resultCountMeta.visibleCount.toLocaleString()}{' '}
{resultCountMeta.unit}
</span>
) : (
<>
{totalSources > 0 && useFluidSearch && (
<span className='ml-2 text-sm font-normal text-gray-500 dark:text-gray-400'>
{completedSources}/{totalSources}
</span>
)}
{isLoading && useFluidSearch && (
<span className='ml-2 inline-block align-middle'>
<span className='inline-block h-3 w-3 animate-spin rounded-full border-2 border-gray-300 border-t-green-500'></span>
</span>
)}
</>
)}
</h2>
{resultCountMeta.isFiltered && (
<span className='inline-flex items-center rounded-full bg-white/80 px-2.5 py-1 font-medium text-gray-500 ring-1 ring-gray-200 dark:bg-gray-900/70 dark:text-gray-400 dark:ring-gray-700'>
{' '}
{resultCountMeta.totalCount.toLocaleString()}{' '}
{resultCountMeta.unit}
</span>
)}
</div>
</div>
{searchQuery && (
<button
onClick={() => {
+199 -64
View File
@@ -1,6 +1,6 @@
'use client';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import React, { useEffect, useRef, useState } from 'react';
interface VirtualScrollableGridProps {
children: React.ReactNode[];
@@ -17,6 +17,32 @@ interface VirtualScrollableGridProps {
const clamp = (n: number, min: number, max: number) => Math.min(max, Math.max(min, n));
const DEFAULT_ROW_HEIGHT = 320;
const MAX_MEASURE_ITEMS = 24;
const SAME_ROW_TOLERANCE = 1;
interface LayoutMetrics {
columns: number;
rowHeight: number;
totalRows: number;
}
const getViewportScrollTop = () => {
if (typeof window === 'undefined') return 0;
return (
window.scrollY ||
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop ||
0
);
};
const parsePixelValue = (value?: string) => {
const parsed = Number.parseFloat(value ?? '');
return Number.isFinite(parsed) ? parsed : 0;
};
export default function VirtualScrollableGrid({
children,
gridClassName,
@@ -26,101 +52,209 @@ export default function VirtualScrollableGrid({
maxContentWidth = 1400,
}: VirtualScrollableGridProps) {
const containerRef = useRef<HTMLDivElement>(null);
const measureRef = useRef<HTMLDivElement>(null);
const columnsRef = useRef<number>(mobileColumns);
const rowHeightRef = useRef<number>(320);
const totalRowsRef = useRef<number>(0);
const measureGridRef = useRef<HTMLDivElement>(null);
const childrenRef = useRef(children);
const rafRef = useRef<number | null>(null);
childrenRef.current = children;
const [layout, setLayout] = useState<LayoutMetrics>(() => ({
columns: Math.max(1, mobileColumns),
rowHeight: DEFAULT_ROW_HEIGHT,
totalRows: Math.ceil(children.length / Math.max(1, mobileColumns)),
}));
const [range, setRange] = useState({ startRow: 0, endRow: 0 });
const computeColumns = () => {
const computeFallbackColumns = () => {
if (typeof window === 'undefined') return mobileColumns;
const width = window.innerWidth;
if (width < 640) return mobileColumns;
const containerWidth = Math.min(width - 32, maxContentWidth);
if (window.innerWidth < 640) return mobileColumns;
const containerWidth = Math.min(
containerRef.current?.clientWidth ?? window.innerWidth - 32,
maxContentWidth
);
return Math.max(mobileColumns, Math.floor(containerWidth / minItemWidth));
};
const updateLayout = () => {
const gapY = window.innerWidth >= 640 ? 80 : 56; // gap-y-14 / sm:gap-y-20
const columns = computeColumns();
columnsRef.current = columns;
totalRowsRef.current = Math.ceil(children.length / Math.max(1, columns));
const readLayout = (): LayoutMetrics => {
const currentChildren = childrenRef.current;
// Measure a single item height (wrapper div around VideoCard) and add vertical gap.
const measureEl = measureRef.current;
const firstItem = measureEl?.querySelector<HTMLElement>('[data-virtual-measure-item]');
const itemH = firstItem?.getBoundingClientRect().height;
if (itemH && Number.isFinite(itemH) && itemH > 0) {
rowHeightRef.current = Math.max(120, Math.round(itemH + gapY));
if (currentChildren.length === 0) {
return {
columns: Math.max(1, mobileColumns),
rowHeight: DEFAULT_ROW_HEIGHT,
totalRows: 0,
};
}
const measureGrid = measureGridRef.current;
const measureItems = measureGrid
? Array.from(
measureGrid.querySelectorAll<HTMLElement>('[data-virtual-measure-item]')
)
: [];
let columns = computeFallbackColumns();
let rowHeight = DEFAULT_ROW_HEIGHT;
if (measureItems.length > 0) {
const firstTop = measureItems[0].offsetTop;
let detectedColumns = 0;
let nextRowTop: number | null = null;
for (const item of measureItems) {
if (Math.abs(item.offsetTop - firstTop) <= SAME_ROW_TOLERANCE) {
detectedColumns += 1;
continue;
}
nextRowTop = item.offsetTop;
break;
}
if (detectedColumns > 0) {
columns = Math.max(1, detectedColumns);
}
const firstItemHeight = measureItems[0].getBoundingClientRect().height;
const rowGap = measureGrid
? parsePixelValue(window.getComputedStyle(measureGrid).rowGap)
: 0;
if (nextRowTop != null && nextRowTop > firstTop) {
rowHeight = Math.max(120, Math.round(nextRowTop - firstTop));
} else if (firstItemHeight > 0) {
rowHeight = Math.max(120, Math.round(firstItemHeight + rowGap));
}
}
return {
columns,
rowHeight,
totalRows: Math.ceil(currentChildren.length / Math.max(1, columns)),
};
};
const updateRange = () => {
const computeRange = (nextLayout: LayoutMetrics) => {
if (nextLayout.totalRows <= 0 || typeof window === 'undefined') {
return { startRow: 0, endRow: 0 };
}
const el = containerRef.current;
if (!el) return;
if (!el || nextLayout.rowHeight <= 0) {
return {
startRow: 0,
endRow: Math.min(nextLayout.totalRows - 1, overscanRows * 2),
};
}
const totalRows = totalRowsRef.current;
if (totalRows <= 0) return;
const rowHeight = rowHeightRef.current;
if (!rowHeight || rowHeight <= 0) return;
// This app uses `document.body` as the actual scroll container (see search page back-to-top logic).
const scrollTop = document.body.scrollTop || 0;
const scrollTop = getViewportScrollTop();
const viewportBottom = scrollTop + window.innerHeight;
const containerTop = el.getBoundingClientRect().top + scrollTop;
const startRow = Math.floor((scrollTop - containerTop) / rowHeight) - overscanRows;
const endRow = Math.ceil((viewportBottom - containerTop) / rowHeight) + overscanRows;
const startRow =
Math.floor((scrollTop - containerTop) / nextLayout.rowHeight) - overscanRows;
const endRow =
Math.ceil((viewportBottom - containerTop) / nextLayout.rowHeight) +
overscanRows;
const clampedStart = clamp(startRow, 0, Math.max(0, totalRows - 1));
const clampedEnd = clamp(endRow, clampedStart, Math.max(0, totalRows - 1));
const clampedStart = clamp(startRow, 0, Math.max(0, nextLayout.totalRows - 1));
const clampedEnd = clamp(
endRow,
clampedStart,
Math.max(0, nextLayout.totalRows - 1)
);
return { startRow: clampedStart, endRow: clampedEnd };
};
const syncLayoutAndRange = () => {
const nextLayout = readLayout();
const nextRange = computeRange(nextLayout);
setLayout((prev) => {
if (
prev.columns === nextLayout.columns &&
prev.rowHeight === nextLayout.rowHeight &&
prev.totalRows === nextLayout.totalRows
) {
return prev;
}
return nextLayout;
});
setRange((prev) => {
if (prev.startRow === clampedStart && prev.endRow === clampedEnd) return prev;
return { startRow: clampedStart, endRow: clampedEnd };
if (
prev.startRow === nextRange.startRow &&
prev.endRow === nextRange.endRow
) {
return prev;
}
return nextRange;
});
};
const scheduleUpdate = () => {
if (typeof window === 'undefined') return;
if (rafRef.current != null) return;
rafRef.current = window.requestAnimationFrame(() => {
rafRef.current = null;
updateLayout();
updateRange();
syncLayoutAndRange();
});
};
useEffect(() => {
updateLayout();
updateRange();
scheduleUpdate();
let isRunning = true;
const rafLoop = () => {
if (!isRunning) return;
const handleScroll = () => {
scheduleUpdate();
window.requestAnimationFrame(rafLoop);
};
rafLoop();
document.body.addEventListener('scroll', scheduleUpdate, { passive: true });
window.addEventListener('resize', scheduleUpdate);
const handleResize = () => {
scheduleUpdate();
};
const bodyEl = document.body;
const documentEl = document.documentElement;
window.addEventListener('scroll', handleScroll, { passive: true });
bodyEl.addEventListener('scroll', handleScroll, { passive: true });
documentEl.addEventListener('scroll', handleScroll, { passive: true });
window.addEventListener('resize', handleResize);
window.addEventListener('orientationchange', handleResize);
let resizeObserver: ResizeObserver | null = null;
if (typeof ResizeObserver !== 'undefined') {
resizeObserver = new ResizeObserver(() => {
scheduleUpdate();
});
if (containerRef.current) {
resizeObserver.observe(containerRef.current);
}
if (measureGridRef.current) {
resizeObserver.observe(measureGridRef.current);
}
}
return () => {
isRunning = false;
document.body.removeEventListener('scroll', scheduleUpdate);
window.removeEventListener('resize', scheduleUpdate);
window.removeEventListener('scroll', handleScroll);
bodyEl.removeEventListener('scroll', handleScroll);
documentEl.removeEventListener('scroll', handleScroll);
window.removeEventListener('resize', handleResize);
window.removeEventListener('orientationchange', handleResize);
resizeObserver?.disconnect();
if (rafRef.current != null) window.cancelAnimationFrame(rafRef.current);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [children.length, overscanRows, mobileColumns, minItemWidth, maxContentWidth]);
const columns = columnsRef.current;
const totalRows = totalRowsRef.current;
const rowHeight = rowHeightRef.current;
const columns = layout.columns;
const totalRows = layout.totalRows;
const rowHeight = layout.rowHeight;
const startIndex = range.startRow * columns;
const endIndexExclusive = Math.min(children.length, (range.endRow + 1) * columns);
@@ -130,19 +264,20 @@ export default function VirtualScrollableGrid({
const bottomSpacerHeight = Math.max(0, (totalRows - range.endRow - 1) * rowHeight);
return (
<div ref={containerRef} className='w-full'>
<div ref={containerRef} className='relative w-full'>
{/* hidden measuring row (first visible row) */}
<div
ref={measureRef}
className='pointer-events-none absolute left-0 top-0 -z-10 opacity-0'
className='pointer-events-none absolute left-0 top-0 -z-10 w-full opacity-0'
aria-hidden='true'
>
<div className={gridClassName}>
{children.slice(0, Math.max(1, columns)).map((child, idx) => (
<div key={`measure-${idx}`} data-virtual-measure-item>
{child}
</div>
))}
<div ref={measureGridRef} className={gridClassName}>
{children
.slice(0, Math.min(children.length, MAX_MEASURE_ITEMS))
.map((child, idx) => (
<div key={`measure-${idx}`} data-virtual-measure-item>
{child}
</div>
))}
</div>
</div>