fix(Navbar): replace IntersectionObserver with scroll-based active section
This commit is contained in:
+12
-20
@@ -48,30 +48,22 @@ export function Navbar() {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const visible = new Set<string>();
|
||||
|
||||
const updateActive = () => {
|
||||
const onScroll = () => {
|
||||
// trigger line = 1/3 from top of viewport (= 2/3 from bottom)
|
||||
const triggerY = window.scrollY + NAVBAR_HEIGHT + (window.innerHeight - NAVBAR_HEIGHT) / 3;
|
||||
let current = "";
|
||||
for (const id of anchorIds) {
|
||||
if (visible.has(id)) { setActiveSection(id); return; }
|
||||
const el = document.getElementById(id);
|
||||
if (!el) continue;
|
||||
const top = el.getBoundingClientRect().top + window.scrollY;
|
||||
if (top <= triggerY) current = id;
|
||||
}
|
||||
setActiveSection("");
|
||||
setActiveSection(current);
|
||||
};
|
||||
|
||||
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 -67% 0px" }
|
||||
);
|
||||
obs.observe(el);
|
||||
return obs;
|
||||
});
|
||||
|
||||
return () => observers.forEach((o) => o?.disconnect());
|
||||
onScroll();
|
||||
window.addEventListener("scroll", onScroll, { passive: true });
|
||||
return () => window.removeEventListener("scroll", onScroll);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
|
||||
Reference in New Issue
Block a user