Skip to content

Commit

Permalink
Improve DB intersection observer logic (#1079)
Browse files Browse the repository at this point in the history
* fix(db): improve intersection observer logic

* Update src/pages/db/_components/Subnav.astro

Co-authored-by: Darius <[email protected]>

* apply suggestions from code review

---------

Co-authored-by: Darius <[email protected]>
  • Loading branch information
natemoo-re and itsMapleLeaf authored Apr 26, 2024
1 parent 60a4cac commit 8a4be11
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions src/pages/db/_components/Subnav.astro
Original file line number Diff line number Diff line change
Expand Up @@ -67,18 +67,19 @@ import Badge from "./Badge.astro";
const targets = Array.from(nav.querySelectorAll("a[href^='#']"))
.map((a) => a.getAttribute("href")?.slice(1))
.filter(Boolean);
const selector = `:is(${targets.map((id) => `[id="${id}"]`).join(",")})`;
const ids = new Map<string, number>();
const io = new IntersectionObserver(
([entry]) => {
if (entry.intersectionRatio > 0.5) {
const element = entry.target.querySelector(
`:is(${targets.map((id) => `[id="${id}"]`).join(",")})`,
);
if (element) {
const link = nav.querySelector(`a[href="#${element.id}"]`);
resetSubnav();
link?.setAttribute("aria-current", "true");
}
const element = entry.target.querySelector(selector);
if (!element) return;
const prevRatio = ids.get(element.id) ?? 0;
if (entry.intersectionRatio > prevRatio) {
const link = nav.querySelector(`a[href="#${element.id}"]`);
resetSubnav();
link?.setAttribute("aria-current", "true");
}
ids.set(element.id, entry.intersectionRatio);
},
{ threshold: [0, 0.4, 0.6, 1] },
);
Expand Down

0 comments on commit 8a4be11

Please sign in to comment.