All files / composables useIntersectionObserver.ts

25.92% Statements 7/27
22.22% Branches 2/9
20% Functions 1/5
25.92% Lines 7/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 73 74 75 76 777x                         7x       241x 241x     241x           241x         241x                                                                                        
import { ref, Ref, onMounted, onUnmounted, watch } from 'vue';
 
/**
 * Sets up a basic IntersectionObserver which attaches to the provided
 * template ref when the component is mounted. Returns a boolean ref which
 * will update to match the current intersection status of the targeted
 * element (true if the element is in view, false if it's scrolled out of view).
 * If IntersectionObserver is not available, the returned ref will always be false.
 *
 * @param templateRef
 * @param observerOptions
 * @return boolean ref
 */
export default function useIntersectionObserver(
	templateRef: Ref<Element|undefined>,
	observerOptions: IntersectionObserverInit
): Ref<boolean> {
	const intersectionRef = ref( false );
	let mounted = false;
 
	// Exit early if not running in a browser
	Iif ( typeof window !== 'object' ) {
		return intersectionRef;
	}
 
	// Exit early if any of the necessary features are not supported by the
	// user's browser.
	if ( !(
		'IntersectionObserver' in window &&
		'IntersectionObserverEntry' in window &&
		'intersectionRatio' in window.IntersectionObserverEntry.prototype
	) ) {
		return intersectionRef;
	}
 
	const observer = new window.IntersectionObserver(
		( entries: IntersectionObserverEntry[] ) => {
			const entry = entries[ 0 ];
			Iif ( entry ) {
				intersectionRef.value = entry.isIntersecting;
			}
		},
		observerOptions
	);
 
	onMounted( () => {
		mounted = true;
		Iif ( templateRef.value ) {
			observer.observe( templateRef.value );
		}
	} );
 
	onUnmounted( () => {
		mounted = false;
		observer.disconnect();
	} );
 
	// If the templateRef changes to point to a different element, disconnect the observer from the
	// old element and observe the new one instead
	watch( templateRef, ( newElement ) => {
		// Don't try to observe the element before the component has been mounted; doing that leads
		// to strange bugs.
		Iif ( !mounted ) {
			return;
		}
		observer.disconnect();
		// Reset the ref back to false, just like when we initialized it. If newElement is set, the
		// observe callback will run and set the ref to true if newElement is visible.
		intersectionRef.value = false;
		Iif ( newElement ) {
			observer.observe( newElement );
		}
	} );
 
	return intersectionRef;
}