2024-10-12 12:46:29 +08:00
|
|
|
import { useEffect } from 'react'
|
|
|
|
|
|
|
|
export const useScrollIntersection = (
|
2024-10-12 16:34:02 +08:00
|
|
|
containerRef: React.RefObject<HTMLDivElement>,
|
2024-10-12 12:46:29 +08:00
|
|
|
anchorRef: React.RefObject<HTMLDivElement>,
|
2024-10-12 16:34:02 +08:00
|
|
|
callback: (isIntersecting: boolean) => void,
|
2024-10-12 12:46:29 +08:00
|
|
|
) => {
|
|
|
|
useEffect(() => {
|
|
|
|
let observer: IntersectionObserver | undefined
|
2024-10-12 16:34:02 +08:00
|
|
|
if (containerRef?.current && anchorRef.current) {
|
2024-10-12 12:46:29 +08:00
|
|
|
observer = new IntersectionObserver((entries) => {
|
2024-10-12 16:34:02 +08:00
|
|
|
const isIntersecting = entries[0].isIntersecting
|
|
|
|
callback(isIntersecting)
|
2024-10-12 12:46:29 +08:00
|
|
|
}, {
|
|
|
|
root: containerRef.current,
|
|
|
|
})
|
|
|
|
observer.observe(anchorRef.current)
|
|
|
|
}
|
|
|
|
return () => observer?.disconnect()
|
2024-10-12 16:34:02 +08:00
|
|
|
}, [containerRef, anchorRef, callback])
|
2024-10-12 12:46:29 +08:00
|
|
|
}
|