mirror of
https://github.com/huhu/rust-search-extension
synced 2024-11-15 08:07:08 +00:00
Refactor scroll highlight with IntersectionObserver API for better performance
This commit is contained in:
parent
b1646773dd
commit
cf890dfcec
1 changed files with 50 additions and 69 deletions
|
@ -1,5 +1,4 @@
|
|||
(async () => {
|
||||
document.addEventListener("DOMContentLoaded", async () => {
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
let versions = [];
|
||||
for (let title of document.querySelectorAll('.markdown-body>h1')) {
|
||||
let version = parseVersion(title)
|
||||
|
@ -43,45 +42,27 @@
|
|||
let readme = document.querySelector(".readme");
|
||||
readme.classList.add("rse-fix-readme");
|
||||
readme.appendChild(ul);
|
||||
});
|
||||
highlight();
|
||||
})();
|
||||
|
||||
function highlightNav(id) {
|
||||
highlight();
|
||||
});
|
||||
|
||||
function highlight() {
|
||||
let items = document.querySelectorAll('.markdown-body>h1>a');
|
||||
const scrollHandler = entries => {
|
||||
entries.forEach(entry => {
|
||||
if (entry.intersectionRatio > 0) {
|
||||
document.querySelectorAll(".rse-version-list-item").forEach((item) => {
|
||||
item.classList.remove("rse-active");
|
||||
});
|
||||
let a = document.querySelector(`.rse-version-list-item a[href$="${id}"]`);
|
||||
if (a) {
|
||||
|
||||
let url = new URL(entry.target.href);
|
||||
let a = document.querySelector(`.rse-version-list-item a[href$="${url.hash}"]`)
|
||||
a.parentElement.parentElement.classList.add("rse-active");
|
||||
}
|
||||
}
|
||||
|
||||
function highlight() {
|
||||
let elementArr = {};
|
||||
|
||||
let currentHeading = "";
|
||||
window.onscroll = () => {
|
||||
document.querySelectorAll('.markdown-body>h1>a').forEach(item => {
|
||||
if (item.href !== "") {
|
||||
let url = new URL(item.href);
|
||||
elementArr[url.hash] = item.getBoundingClientRect().top;
|
||||
}
|
||||
});
|
||||
for (let id in elementArr) {
|
||||
if (!elementArr.hasOwnProperty(id)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (elementArr[id] > 0 && elementArr[id] < 300) {
|
||||
if (currentHeading !== id) {
|
||||
highlightNav(id);
|
||||
currentHeading = id;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
const observer = new IntersectionObserver(scrollHandler);
|
||||
items.forEach(item => observer.observe(item));
|
||||
}
|
||||
|
||||
function parseVersion(title) {
|
||||
|
|
Loading…
Reference in a new issue