2022-09-13 22:47:29 +00:00
|
|
|
import { useEffect, 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
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (elem) {
|
2022-09-13 22:47:29 +00:00
|
|
|
const observer = new IntersectionObserver(([entry]) => {
|
|
|
|
onVisibilityUpdated(entry.isIntersecting)
|
|
|
|
}, {})
|
2022-09-03 02:39:07 +00:00
|
|
|
observer.observe(elem)
|
|
|
|
return () => observer.unobserve(elem)
|
|
|
|
}
|
2022-09-13 22:47:29 +00:00
|
|
|
}, [elem, onVisibilityUpdated])
|
2022-08-09 22:28:27 +00:00
|
|
|
|
|
|
|
return <div ref={setElem} className={className}></div>
|
|
|
|
}
|