simplify menu to avoid breaking anchor link navigation

This commit is contained in:
2024-08-15 00:58:43 +02:00
parent 1b62a7f637
commit 5976d51dda
2 changed files with 21 additions and 32 deletions

View File

@ -9,49 +9,32 @@ import { useInView } from "react-intersection-observer";
import { getSearchPath } from "@/lib/common"; import { getSearchPath } from "@/lib/common";
export const Header = () => { 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({ const { ref: observer, inView: isInView } = useInView({
triggerOnce: false, triggerOnce: false,
initialInView: true, initialInView: true,
}); });
const { replace } = useRouter(); const { replace } = useRouter();
const pathname = usePathname();
const [showMenu, setShowMenu] = useState(false); const [showMenu, setShowMenu] = useState(false);
function toggleMenu() { function toggleMenu() {
setShowMenu(!showMenu); setShowMenu(!showMenu);
} }
// remove ability to scroll when opening menu + keep previous scroll position when closing menu // hide menu on path change
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
useEffect(() => { useEffect(() => {
setShowMenu(false); setShowMenu(false);
setActiveMenuItem(undefined);
}, [pathname]); }, [pathname]);
const [activeMenuItem, setActiveMenuItem] = useState<string | undefined>(
undefined
);
const handleSearch = (e: React.KeyboardEvent<HTMLInputElement>) => { const handleSearch = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key != "Enter") { if (e.key != "Enter") {
return; return;
@ -162,7 +145,9 @@ export const Header = () => {
</a> </a>
</li> </li>
<li className={styles.search}> <li className={styles.search}>
<label htmlFor="search" className="sr-only">Søk</label> <label htmlFor="search" className="sr-only">
Søk
</label>
<input <input
name="search" name="search"
type="text" type="text"

View File

@ -14,6 +14,10 @@ body {
max-width: 100vw; max-width: 100vw;
} }
html:has(header[data-show=true]) {
overflow: hidden;
}
body { body {
height: 100%; height: 100%;
width: 100%; width: 100%;