import { useEffect, useState, type RefObject } from "react"; import { useLocation } from "react-router-dom"; import { useTranslation } from "react-i18next"; import { AnimatePresence, m } from "motion/react"; import { ArrowUp } from "lucide-react"; interface ScrollToTopButtonProps { /** * The scrollable container to watch and scroll back to the top. React 19 * types `useRef(null)` as `RefObject` — the ref genuinely is * null before the element mounts. */ scrollRef: RefObject; } /** Scroll distance (px) past which the button appears. */ const SHOW_AFTER_PX = 600; /** * Floating "back to top" button in the bottom-left corner of the page area * (bottom-right is where pages keep their primary actions and toasts). It * appears once `
` is scrolled past {@link SHOW_AFTER_PX}. */ export function ScrollToTopButton({ scrollRef }: ScrollToTopButtonProps) { const { t } = useTranslation("ui"); const location = useLocation(); const [visible, setVisible] = useState(false); useEffect(() => { const el = scrollRef.current; if (!el) return; let ticking = false; const update = () => { setVisible(el.scrollTop > SHOW_AFTER_PX); ticking = false; }; const onScroll = () => { if (ticking) return; ticking = true; requestAnimationFrame(update); }; // Re-evaluate on mount and whenever the route changes — the same //
persists across pages. update(); el.addEventListener("scroll", onScroll, { passive: true }); return () => el.removeEventListener("scroll", onScroll); }, [scrollRef, location.pathname]); function scrollToTop() { const el = scrollRef.current; if (!el) return; const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches; el.scrollTo({ top: 0, behavior: reduceMotion ? "auto" : "smooth" }); el.focus({ preventScroll: true }); } return ( {visible && ( )} ); }