2024-03-16 04:45:46 +08:00
|
|
|
import React, {
|
|
|
|
useCallback, useMemo, useRef, useState,
|
|
|
|
} from 'react';
|
|
|
|
|
|
|
|
const CURRENT_FIELD = 'current';
|
|
|
|
|
|
|
|
const useIntersectionObserver = (
|
|
|
|
parentRef: React.MutableRefObject<HTMLDivElement | null>,
|
|
|
|
childRef: React.MutableRefObject<HTMLDivElement | null>,
|
2024-06-11 00:08:43 +08:00
|
|
|
threshold: number = 0.1,
|
2024-03-16 04:45:46 +08:00
|
|
|
) => {
|
|
|
|
const observer = useRef<IntersectionObserver | null>(null);
|
|
|
|
const [intersecting, setIntersecting] = useState(false);
|
|
|
|
|
|
|
|
const updateIntersectionObserver = useCallback(
|
|
|
|
(root?: HTMLDivElement | null) => {
|
|
|
|
if (observer.current) {
|
|
|
|
observer.current.disconnect();
|
|
|
|
}
|
|
|
|
const newObserver = new IntersectionObserver((entries) => {
|
|
|
|
entries.forEach((entry) => {
|
|
|
|
const { isIntersecting } = entry;
|
|
|
|
setIntersecting(isIntersecting);
|
|
|
|
});
|
|
|
|
}, {
|
|
|
|
root,
|
2024-06-11 00:08:43 +08:00
|
|
|
threshold,
|
2024-03-16 04:45:46 +08:00
|
|
|
});
|
|
|
|
observer.current = newObserver;
|
|
|
|
},
|
|
|
|
[setIntersecting],
|
|
|
|
);
|
|
|
|
|
|
|
|
const parentRefProxy = useMemo(
|
|
|
|
() => new Proxy(parentRef, {
|
|
|
|
set(target, field, newValue, receiver) {
|
|
|
|
if (field === CURRENT_FIELD) {
|
|
|
|
updateIntersectionObserver(newValue);
|
|
|
|
if (childRef.current && observer.current) {
|
|
|
|
observer.current.observe(childRef.current);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return Reflect.set(target, field, newValue, receiver);
|
|
|
|
},
|
|
|
|
}),
|
|
|
|
[parentRef],
|
|
|
|
);
|
|
|
|
|
|
|
|
const childRefProxy = useMemo(
|
|
|
|
() => new Proxy(childRef, {
|
|
|
|
set(target, field, newValue, receiver) {
|
|
|
|
if (field === CURRENT_FIELD) {
|
|
|
|
if (!observer.current) {
|
|
|
|
updateIntersectionObserver(parentRef.current);
|
|
|
|
} else if (childRef.current) {
|
|
|
|
observer.current.unobserve(childRef.current);
|
|
|
|
}
|
|
|
|
if (newValue instanceof HTMLDivElement && observer.current) {
|
|
|
|
observer.current.observe(newValue);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return Reflect.set(target, field, newValue, receiver);
|
|
|
|
},
|
|
|
|
}),
|
|
|
|
[childRef],
|
|
|
|
);
|
|
|
|
|
|
|
|
return {
|
|
|
|
childRefProxy,
|
|
|
|
parentRefProxy,
|
|
|
|
intersecting,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
export default useIntersectionObserver;
|