Files
aibook-fun/marketing-site/components/Nav.jsx
T

84 lines
2.4 KiB
React

import { useEffect, useRef, useState } from "react";
const LINKS = [
{ href: "#recipe", label: "A recipe" },
{ href: "#contents", label: "Contents" },
{ href: "#letter", label: "Why" },
{ href: "#faq", label: "FAQ" },
];
export default function Nav() {
const [scrolled, setScrolled] = useState(false);
const [open, setOpen] = useState(false);
const navRef = useRef(null);
useEffect(() => {
const onScroll = () => setScrolled(window.scrollY > 12);
onScroll();
window.addEventListener("scroll", onScroll, { passive: true });
return () => window.removeEventListener("scroll", onScroll);
}, []);
// While the mobile menu is open: close on Escape or an outside tap.
useEffect(() => {
if (!open) return;
const onKey = (e) => e.key === "Escape" && setOpen(false);
const onDown = (e) => {
if (navRef.current && !navRef.current.contains(e.target)) setOpen(false);
};
document.addEventListener("keydown", onKey);
document.addEventListener("pointerdown", onDown);
return () => {
document.removeEventListener("keydown", onKey);
document.removeEventListener("pointerdown", onDown);
};
}, [open]);
const close = () => setOpen(false);
return (
<nav ref={navRef} className={`nav${scrolled ? " scrolled" : ""}${open ? " open" : ""}`}>
<div className="nav-in">
<a className="logo" href="#top" onClick={close}>
AIBook<b>.</b>
<span className="dot">fun</span>
</a>
<div className="nav-links">
{LINKS.map((l) => (
<a key={l.href} href={l.href}>
{l.label}
</a>
))}
</div>
<a href="#get" className="btn btn-primary nav-cta">
Get the preview
</a>
<button
type="button"
className="nav-toggle"
aria-label={open ? "Close menu" : "Open menu"}
aria-expanded={open}
aria-controls="mobile-menu"
onClick={() => setOpen((v) => !v)}
>
<span className="bars" aria-hidden="true"></span>
</button>
</div>
<div className="nav-menu" id="mobile-menu">
{LINKS.map((l) => (
<a key={l.href} href={l.href} onClick={close}>
{l.label}
</a>
))}
<a href="#get" className="btn btn-primary" onClick={close}>
Get the preview
</a>
</div>
</nav>
);
}