File size: 2,019 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
import { RefObject, useEffect, useRef, useState } from 'react';

/**
 * Returns whether an element has touched/crossed the viewport's upper boundary,
 * plus or minus a given vertical offset.
 * @param offsetY A vertical offset (in pixels) to add or subtract
 * 		  when determining if the observed element has crossed
 * 		  the viewport's upper boundary
 * @returns A tuple with a reference to the observed element,
 * 			and a boolean indicating whether it's crossed
 * 			the viewport's upper boundary
 */
const useDetectWindowBoundary = (
	offsetY = 0
): [ RefObject< HTMLDivElement | undefined >, boolean | undefined ] => {
	const elementRef = useRef< HTMLDivElement >();
	const observerRef = useRef< IntersectionObserver >();

	const [ borderCrossed, setBorderCrossed ] = useState< boolean | undefined >( undefined );

	useEffect( () => {
		// We can't do anything without a valid reference to an element on the page
		if ( ! elementRef.current ) {
			return;
		}

		// If the observer is already defined, no need to continue
		if ( observerRef.current ) {
			return;
		}

		const handler = ( entries: IntersectionObserverEntry[] ) => {
			if ( ! entries.length ) {
				return;
			}

			// When the observed element crosses out of the top of the viewport,
			// its bounding rectangle will always have a Y coordinate
			// smaller than the value of our offsetY parameter.
			setBorderCrossed( entries[ 0 ].boundingClientRect.y < offsetY );
		};

		// Only trigger the handler when the observed element's
		// intersection ratio becomes 1.0 (fully visible), or
		// when it becomes less than 1.0 (not fully visible)
		observerRef.current = new IntersectionObserver( handler, {
			rootMargin: `${ -1 * offsetY }px 0px 0px 0px`,
			threshold: [ 1 ],
		} );

		observerRef.current.observe( elementRef.current );

		// Stop observing when this hook is unmounted
		return () => observerRef.current?.disconnect?.();
	}, [ offsetY ] );

	return [ elementRef, borderCrossed ];
};

export default useDetectWindowBoundary;