Jotley / website · jotley.ai / src / app / components / ScrollReveal.tsx
| 1 | 'use client'; |
| 2 | |
| 3 | import { useEffect, useRef, useState, ReactNode } from 'react'; |
| 4 | |
| 5 | interface ScrollRevealProps { |
| 6 | children: ReactNode; |
| 7 | className?: string; |
| 8 | delay?: number; |
| 9 | direction?: 'up' | 'down' | 'left' | 'right' | 'none'; |
| 10 | duration?: number; |
| 11 | once?: boolean; |
| 12 | } |
| 13 | |
| 14 | export default function ScrollReveal({ |
| 15 | children, |
| 16 | className = '', |
| 17 | delay = 0, |
| 18 | direction = 'up', |
| 19 | duration = 600, |
| 20 | once = true, |
| 21 | }: ScrollRevealProps) { |
| 22 | const ref = useRef<HTMLDivElement>(null); |
| 23 | const [isVisible, setIsVisible] = useState(false); |
| 24 | |
| 25 | useEffect(() => { |
| 26 | const observer = new IntersectionObserver( |
| 27 | ([entry]) => { |
| 28 | if (entry.isIntersecting) { |
| 29 | setIsVisible(true); |
| 30 | if (once && ref.current) { |
| 31 | observer.unobserve(ref.current); |
| 32 | } |
| 33 | } else if (!once) { |
| 34 | setIsVisible(false); |
| 35 | } |
| 36 | }, |
| 37 | { |
| 38 | threshold: 0.1, |
| 39 | rootMargin: '0px 0px -50px 0px', |
| 40 | } |
| 41 | ); |
| 42 | |
| 43 | if (ref.current) { |
| 44 | observer.observe(ref.current); |
| 45 | } |
| 46 | |
| 47 | return () => observer.disconnect(); |
| 48 | }, [once]); |
| 49 | |
| 50 | const getInitialTransform = () => { |
| 51 | switch (direction) { |
| 52 | case 'up': |
| 53 | return 'translateY(40px)'; |
| 54 | case 'down': |
| 55 | return 'translateY(-40px)'; |
| 56 | case 'left': |
| 57 | return 'translateX(40px)'; |
| 58 | case 'right': |
| 59 | return 'translateX(-40px)'; |
| 60 | case 'none': |
| 61 | return 'none'; |
| 62 | default: |
| 63 | return 'translateY(40px)'; |
| 64 | } |
| 65 | }; |
| 66 | |
| 67 | return ( |
| 68 | <div |
| 69 | ref={ref} |
| 70 | className={className} |
| 71 | style={{ |
| 72 | opacity: isVisible ? 1 : 0, |
| 73 | transform: isVisible ? 'none' : getInitialTransform(), |
| 74 | transition: `opacity ${duration}ms ease-out ${delay}ms, transform ${duration}ms ease-out ${delay}ms`, |
| 75 | }} |
| 76 | > |
| 77 | {children} |
| 78 | </div> |
| 79 | ); |
| 80 | } |