shelving
Version:
Toolkit for using data in JavaScript.
33 lines (32 loc) • 1.41 kB
JavaScript
import { useEffect, useRef } from "react";
/**
* Fires a callback when an element enters the visible scrolling area on the client.
* - Checks that is the last element in its parent.
* - Finds the closest parent above this that scrolls (e.g. `.page`, customisable with `selector` param), then fires the callbacks appropriately.
*/
export function useScrollIntersect(onEnter, onLeave) {
const ref = useRef(null);
useEffect(() => {
const el = ref.current;
if (el) {
const observer = new IntersectionObserver(([entry]) => {
if (entry) {
if (entry.isIntersecting)
onEnter?.();
if (!entry.isIntersecting)
onLeave?.();
}
}, { threshold: [1] });
observer.observe(el);
return () => observer.disconnect();
}
}, [onEnter, onLeave]);
return ref;
}
/** Go through a list of `IntersectionObserverEntry` (from `IntersectionObserver`) and return the index of the one with the highest `intersectionRatio` */
export function getMostVisibleObserverEntry(entries) {
return entries.reduce(_reduceMostVisibleObserverEntry, undefined);
}
function _reduceMostVisibleObserverEntry(mostVisible, current) {
return mostVisible && mostVisible.intersectionRatio > current.intersectionRatio ? mostVisible : current;
}