11import React from 'react' ;
22
3- import { throttle } from 'lodash' ;
3+ import { isEqual , throttle } from 'lodash' ;
44
55import { getArray } from '../../utils' ;
66
77interface UseScrollBasedChunksProps {
8- containerRef : React . RefObject < HTMLElement > ;
8+ parentRef ?: React . RefObject < HTMLElement > ;
9+ tableRef : React . RefObject < HTMLElement > ;
910 totalItems : number ;
10- itemHeight : number ;
11+ rowHeight : number ;
1112 chunkSize : number ;
1213}
1314
1415const THROTTLE_DELAY = 100 ;
1516const CHUNKS_AHEAD_COUNT = 1 ;
1617
1718export const useScrollBasedChunks = ( {
18- containerRef,
19+ parentRef,
20+ tableRef,
1921 totalItems,
20- itemHeight ,
22+ rowHeight ,
2123 chunkSize,
2224} : UseScrollBasedChunksProps ) : number [ ] => {
2325 const [ activeChunks , setActiveChunks ] = React . useState < number [ ] > (
2426 getArray ( 1 + CHUNKS_AHEAD_COUNT ) . map ( ( index ) => index ) ,
2527 ) ;
2628
2729 const calculateActiveChunks = React . useCallback ( ( ) => {
28- const container = containerRef . current ;
29- if ( ! container ) {
30+ const container = parentRef ?. current ;
31+ const table = tableRef . current ;
32+ if ( ! container || ! table ) {
3033 return ;
3134 }
3235
33- const { scrollTop , clientHeight } = container ;
34- const visibleStartIndex = Math . floor ( scrollTop / itemHeight ) ;
36+ const tableScrollTop = Math . max ( container . scrollTop - table . offsetTop , 0 ) ;
37+ const visibleStartIndex = Math . floor ( Math . max ( tableScrollTop , 0 ) / rowHeight ) ;
3538 const visibleEndIndex = Math . min (
36- Math . ceil ( ( scrollTop + clientHeight ) / itemHeight ) ,
39+ Math . ceil ( ( tableScrollTop + container . clientHeight ) / rowHeight ) ,
3740 totalItems - 1 ,
3841 ) ;
3942
@@ -44,16 +47,18 @@ export const useScrollBasedChunks = ({
4447 ( index ) => startChunk + index ,
4548 ) ;
4649
47- setActiveChunks ( newActiveChunks ) ;
48- } , [ chunkSize , containerRef , itemHeight , totalItems ] ) ;
50+ if ( ! isEqual ( activeChunks , newActiveChunks ) ) {
51+ setActiveChunks ( newActiveChunks ) ;
52+ }
53+ } , [ parentRef , tableRef , rowHeight , totalItems , chunkSize , activeChunks ] ) ;
4954
5055 const throttledCalculateActiveChunks = React . useMemo (
5156 ( ) => throttle ( calculateActiveChunks , THROTTLE_DELAY ) ,
5257 [ calculateActiveChunks ] ,
5358 ) ;
5459
5560 React . useEffect ( ( ) => {
56- const container = containerRef . current ;
61+ const container = parentRef ? .current ;
5762 if ( ! container ) {
5863 return undefined ;
5964 }
@@ -63,7 +68,7 @@ export const useScrollBasedChunks = ({
6368 container . removeEventListener ( 'scroll' , throttledCalculateActiveChunks ) ;
6469 throttledCalculateActiveChunks . cancel ( ) ;
6570 } ;
66- } , [ containerRef , throttledCalculateActiveChunks ] ) ;
71+ } , [ parentRef , throttledCalculateActiveChunks ] ) ;
6772
6873 return activeChunks ;
6974} ;
0 commit comments