|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { useState, useEffect, useCallback } from "react"; |
| 4 | +import { motion, AnimatePresence } from "framer-motion"; |
| 5 | +import { ArrowUp } from "lucide-react"; |
| 6 | + |
| 7 | +interface BackToTopProps { |
| 8 | + containerRef?: React.RefObject<HTMLElement | null>; |
| 9 | + threshold?: number; |
| 10 | +} |
| 11 | + |
| 12 | +export default function BackToTop({ containerRef, threshold = 300 }: BackToTopProps) { |
| 13 | + const [isVisible, setIsVisible] = useState(false); |
| 14 | + |
| 15 | + // Throttled scroll handler to prevent layout thrashing and stutter |
| 16 | + useEffect(() => { |
| 17 | + let ticking = false; |
| 18 | + |
| 19 | + const handleScroll = () => { |
| 20 | + if (!ticking) { |
| 21 | + window.requestAnimationFrame(() => { |
| 22 | + let scrollTop = 0; |
| 23 | + if (containerRef?.current) { |
| 24 | + scrollTop = containerRef.current.scrollTop; |
| 25 | + } else { |
| 26 | + scrollTop = window.scrollY; |
| 27 | + } |
| 28 | + |
| 29 | + setIsVisible(scrollTop > threshold); |
| 30 | + ticking = false; |
| 31 | + }); |
| 32 | + ticking = true; |
| 33 | + } |
| 34 | + }; |
| 35 | + |
| 36 | + if (containerRef?.current) { |
| 37 | + const container = containerRef.current; |
| 38 | + container.addEventListener("scroll", handleScroll, { passive: true }); |
| 39 | + return () => container.removeEventListener("scroll", handleScroll); |
| 40 | + } else { |
| 41 | + window.addEventListener("scroll", handleScroll, { passive: true }); |
| 42 | + return () => window.removeEventListener("scroll", handleScroll); |
| 43 | + } |
| 44 | + }, [containerRef, threshold]); |
| 45 | + |
| 46 | + const scrollToTop = () => { |
| 47 | + if (containerRef?.current) { |
| 48 | + containerRef.current.scrollTo({ top: 0, behavior: "smooth" }); |
| 49 | + } else { |
| 50 | + // Use Lenis for window scroll if available, otherwise fallback |
| 51 | + // Since we can't easily access the Lenis instance here without context, |
| 52 | + // we'll rely on native smooth scroll which Lenis intercepts or handles. |
| 53 | + window.scrollTo({ top: 0, behavior: "smooth" }); |
| 54 | + } |
| 55 | + }; |
| 56 | + |
| 57 | + return ( |
| 58 | + <AnimatePresence> |
| 59 | + {isVisible && ( |
| 60 | + <motion.button |
| 61 | + initial={{ opacity: 0, scale: 0.8, y: 20 }} |
| 62 | + animate={{ opacity: 1, scale: 1, y: 0 }} |
| 63 | + exit={{ opacity: 0, scale: 0.8, y: 20 }} |
| 64 | + whileHover={{ scale: 1.1 }} |
| 65 | + whileTap={{ scale: 0.9 }} |
| 66 | + onClick={scrollToTop} |
| 67 | + className="fixed bottom-6 right-6 z-50 p-3 rounded-full bg-white/10 backdrop-blur-md border border-white/20 text-white shadow-lg hover:bg-white/20 transition-colors" |
| 68 | + aria-label="Back to top" |
| 69 | + > |
| 70 | + <ArrowUp className="w-5 h-5" /> |
| 71 | + </motion.button> |
| 72 | + )} |
| 73 | + </AnimatePresence> |
| 74 | + ); |
| 75 | +} |
0 commit comments