Skip to content

Commit

Permalink
Use an IntersectionObserver based ScrollSpy in browsers with no SDA s…
Browse files Browse the repository at this point in the history
…upport
  • Loading branch information
bramus committed Dec 4, 2024
1 parent 5f9470b commit 47a17b1
Showing 1 changed file with 55 additions and 11 deletions.
66 changes: 55 additions & 11 deletions src/components/nav.aside.astro
Original file line number Diff line number Diff line change
Expand Up @@ -107,13 +107,11 @@ const { biomes } = Astro.props;
e.target.lastScrollTop = st <= 0 ? 0 : st;
}

const observer = new IntersectionObserver(
const biomeObserver = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const details = document.querySelector(
`#${entry.target.getAttribute("data-details-target")}`
);
const details = document.querySelector(`#${entry.target.getAttribute("data-details-target")}`);
details.setAttribute("open", "");
}
});
Expand All @@ -123,15 +121,49 @@ const { biomes } = Astro.props;
}
);

const featureObserver = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
const id = entry.target.getAttribute("id");
const $li = document.querySelector(`aside nav details li:has(a[href="#${id}"])`);

if (!$li) return;

if (entry.isIntersecting) {
$li.classList.add('in-view');
} else {
$li.classList.remove('in-view');
}
});
},
{
threshold: 0,
}
);

function observeForSidenav() {
document.querySelectorAll(".biome > section").forEach((biome) => {
observer.observe(biome);
biomeObserver.observe(biome);

if (!CSS.supports('animation-timeline: view()')) {
const features = biome.querySelectorAll('.features-list > div > article');
features.forEach(feature => {
featureObserver.observe(feature);
});
}
});
}

function unobserveForSidenav() {
document.querySelectorAll(".biome > section").forEach((biome) => {
observer.unobserve(biome);
biomeObserver.unobserve(biome);

if (!CSS.supports('animation-timeline: view()')) {
const features = biome.querySelectorAll('.features-list > div > article');
features.forEach(feature => {
featureObserver.unobserve(feature);
});
}
});
}

Expand Down Expand Up @@ -246,14 +278,26 @@ const { biomes } = Astro.props;
position: absolute;
top: 0;
left: 4px;
background: var(--link);


inline-size: 3px;
block-size: 100%;

/* SDA ScrollSpy */
@supports (animation-timeline: view()) {
background: var(--link);
transform: scaleY(0);
animation: i-spy linear;
animation-timeline: var(--_view-timeline);
}

@supports not (animation-timeline: view()) {
background: transparent;
}
}

transform: scaleY(0);
animation: i-spy linear;
animation-timeline: var(--_view-timeline);
/* IntersectionObserver-based ScrollSpy */
&.in-view::before {
background: var(--link);
}

& code {
Expand Down

0 comments on commit 47a17b1

Please sign in to comment.