2022-09-03 02:39:07 +00:00
|
|
|
import { useEffect, useRef, useState } from 'react'
|
2022-08-09 22:28:27 +00:00
|
|
|
import { useEvent } from '../hooks/use-event'
|
|
|
|
|
|
|
|
export function VisibilityObserver(props: {
|
|
|
|
className?: string
|
|
|
|
onVisibilityUpdated: (visible: boolean) => void
|
|
|
|
}) {
|
|
|
|
const { className } = props
|
|
|
|
const [elem, setElem] = useState<HTMLElement | null>(null)
|
|
|
|
const onVisibilityUpdated = useEvent(props.onVisibilityUpdated)
|
2022-09-03 02:39:07 +00:00
|
|
|
const observer = useRef(
|
|
|
|
new IntersectionObserver(([entry]) => {
|
2022-08-09 22:28:27 +00:00
|
|
|
onVisibilityUpdated(entry.isIntersecting)
|
|
|
|
}, {})
|
2022-09-03 02:39:07 +00:00
|
|
|
).current
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (elem) {
|
|
|
|
observer.observe(elem)
|
|
|
|
return () => observer.unobserve(elem)
|
|
|
|
}
|
|
|
|
}, [elem, observer])
|
2022-08-09 22:28:27 +00:00
|
|
|
|
|
|
|
return <div ref={setElem} className={className}></div>
|
|
|
|
}
|