Path: blob/main/frontend/ts/indexhighlighter.ts
3855 views
const threshold = 11const windowTriggerMargins = '-50px 0px -66% 0px'23let activeSectionId = ''45const onActiveSectionChanged = function (prevSectionId: string, nextSectionId: string) {6const prevSectionLink = document.querySelector('a.c-sidebar__entry.c-sidebar__entry--progress') as HTMLAnchorElement7const nextSectionLink = document.querySelector(`a.c-sidebar__entry[href="#${nextSectionId}"]`) as HTMLAnchorElement8const activeClass = ' c-sidebar__entry--active c-sidebar__entry--progress '910if (nextSectionLink) {11if (prevSectionLink) {12prevSectionLink.className = (prevSectionLink.className.replace(activeClass, ''))13}14nextSectionLink.className += activeClass1516const linkOffset = nextSectionLink.offsetTop17const sectionId = window.textbook?.course?.section18const connection = document.querySelector(`[data-section-id="${sectionId}"] .connection--progress`) as HTMLDivElement19if (connection) {20connection.style.height = `${linkOffset}px`21}22}23}2425const onSectionVisibility = function (entries: Array<IntersectionObserverEntry>) {26let highestTopValue = Infinity2728entries.forEach((entry) => {29const { target, boundingClientRect, rootBounds } = entry3031if (rootBounds) {32const targetTop = boundingClientRect.top33const triggerWindowBottom = rootBounds.bottom34const onTop = targetTop >= 0 && targetTop <= triggerWindowBottom3536if (onTop && targetTop < highestTopValue) {37if (target.id && activeSectionId !== target.id) {38onActiveSectionChanged(activeSectionId, target.id)39activeSectionId = target.id40}41highestTopValue = targetTop42}43}44})45}4647const initIndexHighlight = function () {48const observer = new IntersectionObserver(49onSectionVisibility,50{51root: null,52rootMargin: windowTriggerMargins,53threshold54}55)5657document.querySelectorAll(':is(h1, h2, h3, h4) > a[id]')58.forEach((section) => {59(observer as IntersectionObserver).observe(section)60})6162window.addEventListener('beforeunload', function (e) {63observer && observer.disconnect()64})65}6667export {68initIndexHighlight69}707172