"use client"; import Link from "next/link"; import { usePathname } from "next/navigation"; import { useEffect, useId, useRef, useState } from "react"; import { NavIcon, type NavIconName } from "./NavIcon"; export interface NavItem { href: string; label: string; icon: NavIconName; /** One line under the label in a dropdown. */ note?: string; } export interface NavGroup { label: string; icon: NavIconName; /** The dropdown's small heading. */ title: string; items: NavItem[]; } const isGroup = (e: NavItem | NavGroup): e is NavGroup => "items" in e; /** * The app's menu row: items with a gold mark, and a group (the free pages) * that opens on a click as a dropdown. Closes on a click outside, Escape or * moving to another page. */ export function NavLinks({ entries }: { entries: (NavItem | NavGroup)[] }) { const pathname = usePathname(); const here = (href: string) => pathname.startsWith(href); return ( {entries.map((e) => isGroup(e) ? ( here(i.href))} here={here} /> ) : ( {e.label} ), )} ); } function Dropdown({ group, active, here, }: { group: NavGroup; active: boolean; here: (href: string) => boolean; }) { const [open, setOpen] = useState(false); const box = useRef(null); const button = useRef(null); const id = 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]); return ( setOpen((o) => !o)} > {group.label} {open && ( {group.title} {group.items.map((i) => ( {i.label} {i.note && {i.note}} ))} )} ); }