|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { usePathname } from "next/navigation"; |
| 4 | +import { useEffect } from "react"; |
| 5 | + |
| 6 | +const REVEAL_SELECTOR = [ |
| 7 | + "main section", |
| 8 | + "main > article > header", |
| 9 | + "main > article > div", |
| 10 | + "footer", |
| 11 | +].join(","); |
| 12 | + |
| 13 | +export default function SiteScrollMotion() { |
| 14 | + const pathname = usePathname(); |
| 15 | + |
| 16 | + useEffect(() => { |
| 17 | + const elements = Array.from( |
| 18 | + document.querySelectorAll<HTMLElement>(REVEAL_SELECTOR) |
| 19 | + ); |
| 20 | + const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches; |
| 21 | + |
| 22 | + if (reduceMotion || !("IntersectionObserver" in window)) { |
| 23 | + elements.forEach((element) => { |
| 24 | + element.dataset.scrollReveal = "visible"; |
| 25 | + }); |
| 26 | + |
| 27 | + return () => { |
| 28 | + elements.forEach((element) => delete element.dataset.scrollReveal); |
| 29 | + }; |
| 30 | + } |
| 31 | + |
| 32 | + const viewportThreshold = window.innerHeight * 0.9; |
| 33 | + const observer = new IntersectionObserver( |
| 34 | + (entries) => { |
| 35 | + entries.forEach((entry) => { |
| 36 | + if (!entry.isIntersecting) { |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + const element = entry.target as HTMLElement; |
| 41 | + element.dataset.scrollReveal = "visible"; |
| 42 | + observer.unobserve(element); |
| 43 | + }); |
| 44 | + }, |
| 45 | + { |
| 46 | + threshold: 0.08, |
| 47 | + rootMargin: "0px 0px -8% 0px", |
| 48 | + } |
| 49 | + ); |
| 50 | + |
| 51 | + elements.forEach((element) => { |
| 52 | + const bounds = element.getBoundingClientRect(); |
| 53 | + const initiallyVisible = bounds.top < viewportThreshold && bounds.bottom > 0; |
| 54 | + |
| 55 | + element.dataset.scrollReveal = initiallyVisible ? "visible" : "pending"; |
| 56 | + |
| 57 | + if (!initiallyVisible) { |
| 58 | + observer.observe(element); |
| 59 | + } |
| 60 | + }); |
| 61 | + |
| 62 | + return () => { |
| 63 | + observer.disconnect(); |
| 64 | + elements.forEach((element) => delete element.dataset.scrollReveal); |
| 65 | + }; |
| 66 | + }, [pathname]); |
| 67 | + |
| 68 | + return null; |
| 69 | +} |
0 commit comments