diff --git a/app/components/Navbar.tsx b/app/components/Navbar.tsx index 63615a0..f66e4f4 100644 --- a/app/components/Navbar.tsx +++ b/app/components/Navbar.tsx @@ -33,8 +33,13 @@ const navLinks = [ { label: "Shop", href: "/shop" }, ]; +const anchorIds = navLinks + .filter((l) => l.href.startsWith("#")) + .map((l) => l.href.slice(1)); + export function Navbar() { const [scrolled, setScrolled] = useState(false); + const [activeSection, setActiveSection] = useState(""); useEffect(() => { const onScroll = () => setScrolled(window.scrollY > 8); @@ -42,6 +47,33 @@ export function Navbar() { return () => window.removeEventListener("scroll", onScroll); }, []); + useEffect(() => { + const visible = new Set(); + + const updateActive = () => { + for (const id of anchorIds) { + if (visible.has(id)) { setActiveSection(id); return; } + } + setActiveSection(""); + }; + + const observers = anchorIds.map((id) => { + const el = document.getElementById(id); + if (!el) return null; + const obs = new IntersectionObserver( + ([entry]) => { + entry.isIntersecting ? visible.add(id) : visible.delete(id); + updateActive(); + }, + { rootMargin: "-100px 0px -50% 0px" } + ); + obs.observe(el); + return obs; + }); + + return () => observers.forEach((o) => o?.disconnect()); + }, []); + return (
{link.label}