File size: 1,827 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
63
64
65
66
67
68
69
70
71
72
import { useEvent } from '@wordpress/compose';
import { useState, useEffect } from 'react';

/**
 * Tracks if an element contains overflow and on which end by tracking the
 * first and last child elements with an `IntersectionObserver` in relation
 * to the parent element.
 *
 * Note that the returned value will only indicate whether the first or last
 * element is currently "going out of bounds" but not whether it happens on
 * the X or Y axis.
 */
export function useTrackOverflow(
	parent: HTMLElement | undefined | null,
	children: {
		first: HTMLElement | undefined | null;
		last: HTMLElement | undefined | null;
	}
) {
	const [ first, setFirst ] = useState( false );
	const [ last, setLast ] = useState( false );
	const [ observer, setObserver ] = useState< IntersectionObserver >();

	const callback: IntersectionObserverCallback = useEvent( ( entries ) => {
		for ( const entry of entries ) {
			if ( entry.target === children.first ) {
				setFirst( ! entry.isIntersecting );
			}
			if ( entry.target === children.last ) {
				setLast( ! entry.isIntersecting );
			}
		}
	} );

	useEffect( () => {
		if ( ! parent || ! window.IntersectionObserver ) {
			return;
		}
		const newObserver = new IntersectionObserver( callback, {
			root: parent,
			threshold: 0.9,
		} );
		setObserver( newObserver );

		return () => newObserver.disconnect();
	}, [ callback, parent ] );

	useEffect( () => {
		if ( ! observer ) {
			return;
		}

		if ( children.first ) {
			observer.observe( children.first );
		}
		if ( children.last ) {
			observer.observe( children.last );
		}

		return () => {
			if ( children.first ) {
				observer.unobserve( children.first );
			}
			if ( children.last ) {
				observer.unobserve( children.last );
			}
		};
	}, [ children.first, children.last, observer ] );

	return { first, last };
}