@@ -2,60 +2,65 @@ import React from 'react';
22
33import { throttle } from 'lodash' ;
44
5+ import { getArray } from '../../utils' ;
6+
57interface UseScrollBasedChunksProps {
6- containerRef : React . RefObject < HTMLElement > | null ;
8+ containerRef : React . RefObject < HTMLElement > ;
79 totalItems : number ;
810 itemHeight : number ;
911 chunkSize : number ;
1012}
1113
12- const THROTTLING_TIMEOUT = 100 ;
14+ const THROTTLE_DELAY = 100 ;
1315
1416export const useScrollBasedChunks = ( {
1517 containerRef,
1618 totalItems,
1719 itemHeight,
1820 chunkSize,
19- } : UseScrollBasedChunksProps ) => {
21+ } : UseScrollBasedChunksProps ) : number [ ] => {
2022 const [ activeChunks , setActiveChunks ] = React . useState < number [ ] > ( [ 0 ] ) ;
2123
22- const handleScroll = React . useCallback ( ( ) => {
23- if ( ! containerRef ?. current ) {
24+ const calculateActiveChunks = React . useCallback ( ( ) => {
25+ const container = containerRef . current ;
26+ if ( ! container ) {
2427 return ;
2528 }
2629
27- const { scrollTop, clientHeight} = containerRef . current ;
28-
30+ const { scrollTop, clientHeight} = container ;
2931 const visibleStartIndex = Math . floor ( scrollTop / itemHeight ) ;
3032 const visibleEndIndex = Math . min (
3133 Math . ceil ( ( scrollTop + clientHeight ) / itemHeight ) ,
32- Math . max ( totalItems - 1 , 0 ) ,
34+ totalItems - 1 ,
3335 ) ;
3436
3537 const startChunk = Math . floor ( visibleStartIndex / chunkSize ) ;
3638 const endChunk = Math . floor ( visibleEndIndex / chunkSize ) ;
3739
38- const newActiveChunks = Array . from (
39- { length : endChunk - startChunk + 1 } ,
40- ( _ , index ) => startChunk + index ,
40+ const newActiveChunks = getArray ( endChunk - startChunk + 1 ) . map (
41+ ( index ) => startChunk + index ,
4142 ) ;
4243
4344 setActiveChunks ( newActiveChunks ) ;
4445 } , [ chunkSize , containerRef , itemHeight , totalItems ] ) ;
4546
47+ const throttledCalculateActiveChunks = React . useMemo (
48+ ( ) => throttle ( calculateActiveChunks , THROTTLE_DELAY ) ,
49+ [ calculateActiveChunks ] ,
50+ ) ;
51+
4652 React . useEffect ( ( ) => {
47- const containerElement = containerRef ? .current ;
48- if ( ! containerElement ) {
53+ const container = containerRef . current ;
54+ if ( ! container ) {
4955 return undefined ;
5056 }
5157
52- const throttledHandleScroll = throttle ( handleScroll , THROTTLING_TIMEOUT ) ;
53- containerElement . addEventListener ( 'scroll' , throttledHandleScroll ) ;
54-
58+ container . addEventListener ( 'scroll' , throttledCalculateActiveChunks ) ;
5559 return ( ) => {
56- containerElement . removeEventListener ( 'scroll' , throttledHandleScroll ) ;
60+ container . removeEventListener ( 'scroll' , throttledCalculateActiveChunks ) ;
61+ throttledCalculateActiveChunks . cancel ( ) ;
5762 } ;
58- } , [ containerRef , handleScroll ] ) ;
63+ } , [ containerRef , throttledCalculateActiveChunks ] ) ;
5964
6065 return activeChunks ;
6166} ;
0 commit comments