Files
sorsfonalak/services/frontend/src/components/MobileMenu.tsx
T

84 lines
2.7 KiB
TypeScript
Raw Normal View History

"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useId, useRef, useState } from "react";
export interface MenuSection {
/** A small heading above the group (e.g. "Ingyenes"). */
title?: string;
links: { href: string; label: string }[];
}
/**
* The menu behind the ☰ button on narrow screens (the header's link rows are
* hidden there, see globals.css). Closes on a click outside, Escape, or
* moving to another page. `className` sets the width from which it shows.
*/
export function MobileMenu({ sections, className }: { sections: MenuSection[]; className: string }) {
const [open, setOpen] = useState(false);
const box = useRef<HTMLDivElement>(null);
const button = useRef<HTMLButtonElement>(null);
const panelId = useId();
const pathname = usePathname();
useEffect(() => setOpen(false), [pathname]);
useEffect(() => {
if (!open) return;
const outside = (e: PointerEvent) => {
if (box.current && !box.current.contains(e.target as Node)) setOpen(false);
};
const escape = (e: KeyboardEvent) => {
if (e.key === "Escape") {
setOpen(false);
button.current?.focus();
}
};
document.addEventListener("pointerdown", outside);
document.addEventListener("keydown", escape);
return () => {
document.removeEventListener("pointerdown", outside);
document.removeEventListener("keydown", escape);
};
}, [open]);
const current = (href: string) => !href.includes("#") && pathname.startsWith(href);
return (
<div className={`mobile-menu ${className}`} ref={box}>
<button
ref={button}
type="button"
className="mobile-menu-button"
aria-expanded={open}
aria-controls={panelId}
aria-label={open ? "Menü bezárása" : "Menü"}
onClick={() => setOpen((o) => !o)}
>
<svg viewBox="0 0 24 24" aria-hidden="true">
{open ? <path d="M6 6l12 12M18 6L6 18" /> : <path d="M4 7h16M4 12h16M4 17h16" />}
</svg>
</button>
{open && (
<nav id={panelId} className="mobile-menu-panel" aria-label="Menü">
{sections.map((s, i) => (
<div key={i} className="mobile-menu-group">
{s.title && <span className="lp-free-label">{s.title}</span>}
{s.links.map((l) => (
<Link
key={l.href}
href={l.href}
aria-current={current(l.href) ? "page" : undefined}
onClick={() => setOpen(false)}
>
{l.label}
</Link>
))}
</div>
))}
</nav>
)}
</div>
);
}