From 5976d51dda5a569119850f4d5a7e3d8670c0c97c Mon Sep 17 00:00:00 2001 From: Jonas Braathen Date: Thu, 15 Aug 2024 00:58:43 +0200 Subject: [PATCH] simplify menu to avoid breaking anchor link navigation --- web/src/components/layout/Header.tsx | 45 ++++++++++------------------ web/src/css/base.scss | 8 +++-- 2 files changed, 21 insertions(+), 32 deletions(-) diff --git a/web/src/components/layout/Header.tsx b/web/src/components/layout/Header.tsx index 0b4439d..8eb286a 100644 --- a/web/src/components/layout/Header.tsx +++ b/web/src/components/layout/Header.tsx @@ -9,49 +9,32 @@ import { useInView } from "react-intersection-observer"; import { getSearchPath } from "@/lib/common"; export const Header = () => { + /* + This component depends on the following CSS rule in base.css to prevent scrolling + the body while the menu is open: + + html:has(header[data-show=true]) { + overflow: hidden; + } + */ + const { ref: observer, inView: isInView } = useInView({ triggerOnce: false, initialInView: true, }); const { replace } = useRouter(); - + const pathname = usePathname(); const [showMenu, setShowMenu] = useState(false); + function toggleMenu() { setShowMenu(!showMenu); } - // remove ability to scroll when opening menu + keep previous scroll position when closing menu - useEffect(() => { - if (showMenu) { - const scrollY = window.scrollY; - document.body.style.position = "fixed"; - document.body.style.top = `-${scrollY}px`; - } else { - const scrollY = parseInt(document.body.style.top || "0") * -1; - document.body.style.position = ""; - document.body.style.top = ""; - window.scrollTo(0, scrollY); - } - }, [showMenu]); - - const pathname = usePathname(); - // reset scroll position on path change - useEffect(() => { - if (!showMenu) { - window.scrollTo(0, 0); - } - }, [pathname, showMenu]); - - // hide menu and reset active menu item on path change + // hide menu on path change useEffect(() => { setShowMenu(false); - setActiveMenuItem(undefined); }, [pathname]); - const [activeMenuItem, setActiveMenuItem] = useState( - undefined - ); - const handleSearch = (e: React.KeyboardEvent) => { if (e.key != "Enter") { return; @@ -162,7 +145,9 @@ export const Header = () => {
  • - +