@open-condo/miniapp-utils
Version:
A set of helper functions / components / hooks used to build new condo apps fast
51 lines • 1.59 kB
JavaScript
// src/hooks/useIntersectionObserver.ts
import { useEffect, useRef, useState } from "react";
function useIntersectionObserver({
threshold = 0,
root = null,
rootMargin = "0%",
onChange
} = {}) {
const [ref, setRef] = useState(null);
const [state, setState] = useState(() => ({
isIntersecting: false,
entry: void 0
}));
const callbackRef = useRef();
callbackRef.current = onChange;
useEffect(() => {
if (!ref) return;
if (!("IntersectionObserver" in window)) return;
const observer = new IntersectionObserver((entries) => {
const thresholds = observer.thresholds;
entries.forEach((entry) => {
const isIntersecting = entry.isIntersecting && thresholds.some((threshold2) => entry.intersectionRatio >= threshold2);
setState({ isIntersecting, entry });
if (callbackRef.current) {
callbackRef.current(isIntersecting, entry);
}
});
}, { threshold, root, rootMargin });
observer.observe(ref);
return () => {
observer.disconnect();
};
}, [ref, root, rootMargin, threshold]);
const prevRef = useRef(null);
useEffect(() => {
var _a;
if (!ref && ((_a = state.entry) == null ? void 0 : _a.target) && prevRef.current !== state.entry.target) {
prevRef.current = state.entry.target;
setState({ isIntersecting: false, entry: void 0 });
}
}, [ref, state.entry]);
return {
entry: state.entry,
ref: setRef,
isIntersecting: state.isIntersecting
};
}
export {
useIntersectionObserver
};
//# sourceMappingURL=useIntersectionObserver.mjs.map