aboutsummaryrefslogtreecommitdiff
path: root/templates/partials/doc/page_toc_script.html
blob: efe4bac207522110bc6a7235d9ce0bdff9531fa1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<script>

const menuBarHeight = document.querySelector("nav.navbar").clientHeight;
const mainTocMenuWidth = document.getElementById('main-toc-menu').clientWidth;
const tocItems = document.querySelectorAll(".toc");
const navSections = new Array(tocItems.length);

// Page content
/*
    Focus effect on current section anchor when user scrolls.
*/

tocItems.forEach((el, i) => {
    let id = el.getAttribute("id").substring(5);
    navSections[i] = document.getElementById(id);
})

function isVisible(tocIndex) {
    const current = navSections[tocIndex];
    const next = tocIndex < tocItems.length - 1 ? navSections[tocIndex + 1]
        : document.querySelectorAll("section.section").item(1);

    const c = current.getBoundingClientRect();
    if (next) {
      const n = next.getBoundingClientRect();
      const h = (window.innerHeight || document.documentElement.clientHeight);

      return (c.top <= h) && (n.top - menuBarHeight >= 0);
    } else {
      const h = (window.innerHeight || document.documentElement.clientHeight);

      return (c.top <= h);
    }
}

function activateIfVisible() {
    for (b = true, i = 0; i < tocItems.length; i++) {
        if (b && isVisible(i)) {
            tocItems[i].classList.add('is-active');
            b = false;
        } else
            tocItems[i].classList.remove('is-active');
    }
}

var isTicking = null;
window.addEventListener('scroll', () => {
    if (!isTicking) {
        window.requestAnimationFrame(() => {
            activateIfVisible();
            isTicking = false;
        });
        isTicking = true;
    }
}, false);

</script>