File size: 1,639 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { LegacyRef, useEffect, useRef, useState } from 'react';

type Options = {
	offset?: string;
	shouldStop?: boolean;
	onLoadMore?: () => Promise< void >;
};

/** useInfiniteScroll */
export function useInfiniteScroll( options?: Options ) {
	const { offset = '0px', shouldStop = false, onLoadMore } = options ?? {};

	const [ isLoading, setIsLoading ] = useState( false );
	const observerRef = useRef< IntersectionObserver >();
	const targetRef = useRef( document.createElement( 'div' ) );

	const containerRef: LegacyRef< HTMLElement > = ( container ) => {
		if ( container ) {
			container.append( targetRef.current );
			container.style.position = 'relative';
		}
	};

	useEffect( () => {
		const target = targetRef.current;
		target.toggleAttribute( 'data-infinite-scroll-detector', true );
		target.style.position = 'absolute';
		target.style.bottom = offset;
		if ( target.offsetTop < 0 ) {
			target.style.bottom = '0px';
		}
	}, [ offset, isLoading ] );

	useEffect( () => {
		const observe = observerRef.current;
		if ( observe ) {
			observe.disconnect();
		}

		async function handler( [ { isIntersecting } ]: IntersectionObserverEntry[] ) {
			if ( isIntersecting && ! isLoading && ! shouldStop && typeof onLoadMore === 'function' ) {
				setIsLoading( true );
				await onLoadMore();
				setIsLoading( false );
			}
		}

		observerRef.current = new IntersectionObserver( handler as IntersectionObserverCallback, {
			threshold: 0,
		} );

		observerRef.current.observe( targetRef.current );

		return () => observe?.disconnect();
	}, [ isLoading, onLoadMore, shouldStop ] );

	return {
		isLoading,
		containerRef,
	};
}