| 1 |
import { useEffect, useRef } from 'react'; |
| 2 |
|
| 3 |
export const ScrollIntoViewOnce = ({ children, ...props }) => { |
| 4 |
const ref = useRef(null); |
| 5 |
const once = useRef(false); |
| 6 |
|
| 7 |
useEffect(() => { |
| 8 |
if (!ref.current || once.current) return; |
| 9 |
const c = ref.current; |
| 10 |
// only scroll if 50% isnt visible |
| 11 |
const rect = c.getBoundingClientRect(); |
| 12 |
const windowHeight = |
| 13 |
window.innerHeight || document.documentElement.clientHeight; |
| 14 |
const elementHeight = rect.height; |
| 15 |
const visibleTop = Math.max(rect.top, 0); |
| 16 |
const visibleBottom = Math.min(rect.bottom, windowHeight); |
| 17 |
const visibleHeight = Math.max(0, visibleBottom - visibleTop); |
| 18 |
const visibleRatio = visibleHeight / elementHeight; |
| 19 |
|
| 20 |
if (visibleRatio >= 0.5) return; |
| 21 |
c.scrollIntoView({ behavior: 'smooth', block: 'end' }); |
| 22 |
once.current = true; |
| 23 |
}, []); |
| 24 |
|
| 25 |
return ( |
| 26 |
<div ref={ref} {...props}> |
| 27 |
{children} |
| 28 |
</div> |
| 29 |
); |
| 30 |
}; |
| 31 |
|