|
| 1 | +import React from 'react'; |
| 2 | + |
| 3 | +interface UseViewportChunkSizeParams { |
| 4 | + limit: number | 'viewport'; |
| 5 | + parentRef: React.RefObject<HTMLElement>; |
| 6 | + rowHeight: number; |
| 7 | + defaultChunkSize?: number; |
| 8 | +} |
| 9 | + |
| 10 | +/** |
| 11 | + * Hook that calculates the number of rows that can fit in the viewport |
| 12 | + * Returns calculated chunk size based on viewport height or the provided limit if it's a number |
| 13 | + */ |
| 14 | +export const useViewportChunkSize = ({ |
| 15 | + limit, |
| 16 | + parentRef, |
| 17 | + rowHeight, |
| 18 | + defaultChunkSize = 20, |
| 19 | +}: UseViewportChunkSizeParams): number => { |
| 20 | + // State to store calculated chunk size for viewport mode |
| 21 | + const [calculatedChunkSize, setCalculatedChunkSize] = React.useState( |
| 22 | + typeof limit === 'number' ? limit : defaultChunkSize, |
| 23 | + ); |
| 24 | + |
| 25 | + // Calculate rows that fit in viewport and update when container size changes |
| 26 | + React.useEffect(() => { |
| 27 | + if (limit !== 'viewport' || !parentRef.current) { |
| 28 | + if (typeof limit === 'number') { |
| 29 | + setCalculatedChunkSize(limit); |
| 30 | + } |
| 31 | + return undefined; |
| 32 | + } |
| 33 | + |
| 34 | + // Store a reference to the current element |
| 35 | + const currentElement = parentRef.current; |
| 36 | + |
| 37 | + const calculateVisibleRows = () => { |
| 38 | + const viewportHeight = currentElement.clientHeight; |
| 39 | + const visibleRows = Math.floor(viewportHeight / rowHeight); |
| 40 | + setCalculatedChunkSize(Math.max(visibleRows, 1)); |
| 41 | + }; |
| 42 | + |
| 43 | + // Calculate initially |
| 44 | + calculateVisibleRows(); |
| 45 | + |
| 46 | + // Set up ResizeObserver to recalculate on parent container size changes |
| 47 | + const resizeObserver = new ResizeObserver(calculateVisibleRows); |
| 48 | + resizeObserver.observe(currentElement); |
| 49 | + |
| 50 | + return () => { |
| 51 | + // Use the stored reference in the cleanup |
| 52 | + resizeObserver.unobserve(currentElement); |
| 53 | + resizeObserver.disconnect(); |
| 54 | + }; |
| 55 | + }, [limit, parentRef, rowHeight]); |
| 56 | + |
| 57 | + // Return the calculated or provided chunk size |
| 58 | + return typeof limit === 'number' ? limit : calculatedChunkSize; |
| 59 | +}; |
0 commit comments