diff --git a/src/components/Navbar.tsx b/src/components/Navbar.tsx index 052a855c..b03386a8 100644 --- a/src/components/Navbar.tsx +++ b/src/components/Navbar.tsx @@ -2,8 +2,8 @@ import { motion, AnimatePresence } from 'framer-motion'; import { useSession } from 'next-auth/react'; -import { usePathname, useRouter } from 'next/navigation'; -import React, { useState, useCallback, useMemo } from 'react'; +import { usePathname } from 'next/navigation'; +import React, { useState, useCallback, useMemo, useEffect } from 'react'; import Link from 'next/link'; import { ArrowLeft, Menu, Search, X } from 'lucide-react'; import { Button } from './ui/button'; @@ -12,9 +12,10 @@ import ThemeToggler from './ThemeToggler'; import ProfileDropdown from './profile-menu/ProfileDropdown'; import { SearchBar } from './search/SearchBar'; +const scrollPositions = new Map(); + export const Navbar = () => { const { data: session } = useSession(); - const router = useRouter(); const [isMenuOpen, setIsMenuOpen] = useState(false); const [isSearchOpen, setIsSearchOpen] = useState(false); const pathname = usePathname(); @@ -40,6 +41,34 @@ export const Navbar = () => { [], ); + // Save scroll position when leaving a page + + useEffect(() => { + const handleScroll = () => { + scrollPositions.set(pathname, window.scrollY); + }; + + window.addEventListener('scroll', handleScroll); + + return () => window.removeEventListener('scroll', handleScroll); + }, [pathname]); + + // Custom back navigation with scroll position restoration + + const handleBack = useCallback(() => { + scrollPositions.set(pathname, window.scrollY); + + // Use window.history to go back + window.history.back(); + + // Restore scroll position after a short delay to ensure the page has loaded + setTimeout(() => { + const previousPath = window.location.pathname; + const savedPosition = scrollPositions.get(previousPath) || 0; + window.scrollTo(0, savedPosition); + }, 100); + }, [pathname]); + return ( <> { > {session?.user && pathname !== '/home' && (