Fix search card virtualization and result count
This commit is contained in:
@@ -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>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user