File size: 1,748 Bytes
f0743f4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | import { useCallback, useMemo } from 'react';
interface UseVirtualGridProps {
itemCount: number;
containerWidth: number;
itemHeight: number;
gapSize: number;
mobileColumnsCount: number;
desktopColumnsCount: number;
mobileBreakpoint: number;
}
interface UseVirtualGridReturn {
cardsPerRow: number;
rowCount: number;
rowHeight: number;
getRowItems: (rowIndex: number, items: any[]) => any[];
}
/**
* Custom hook for virtual grid calculations
* Handles responsive grid layout and item positioning for virtualized lists
*/
export const useVirtualGrid = ({
itemCount,
containerWidth,
itemHeight,
gapSize,
mobileColumnsCount,
desktopColumnsCount,
mobileBreakpoint = 768,
}: UseVirtualGridProps): UseVirtualGridReturn => {
// Calculate cards per row based on container width
const cardsPerRow = useMemo(() => {
return containerWidth >= mobileBreakpoint ? desktopColumnsCount : mobileColumnsCount;
}, [containerWidth, mobileBreakpoint, desktopColumnsCount, mobileColumnsCount]);
// Calculate total number of rows needed
const rowCount = useMemo(() => {
return Math.ceil(itemCount / cardsPerRow);
}, [itemCount, cardsPerRow]);
// Calculate row height including gap
const rowHeight = useMemo(() => {
return itemHeight + gapSize;
}, [itemHeight, gapSize]);
// Get items for a specific row
const getRowItems = useCallback(
(rowIndex: number, items: any[]) => {
const startIndex = rowIndex * cardsPerRow;
const endIndex = Math.min(startIndex + cardsPerRow, items.length);
return items.slice(startIndex, endIndex);
},
[cardsPerRow],
);
return {
cardsPerRow,
rowCount,
rowHeight,
getRowItems,
};
};
export default useVirtualGrid;
|