mediawiki-skins-Citizen/resources/skins.citizen.scripts/tableOfContents.js

48 lines
1.5 KiB
JavaScript
Raw Normal View History

const ACTIVE_ITEM_CLASS = 'toc__item--active';
2020-06-17 03:16:45 +00:00
/**
* Toggle active HTML class to items in table of content based on user viewport.
*
* @param {Element} toc TOC element
* @return {void}
2020-06-17 03:16:45 +00:00
*/
function initToC( toc ) {
const
headlines = document.querySelectorAll( '.mw-headline' ),
marginTop = '-' + window.getComputedStyle( document.documentElement ).getPropertyValue( 'scroll-padding-top' );
for ( let i = 0; i < headlines.length; i++ ) {
/* eslint-disable compat/compat */
const observer = new IntersectionObserver( ( entry ) => {
/* eslint-enable compat/compat */
if ( entry[ 0 ].isIntersecting ) {
const
headlineId = headlines[ i ].id,
// Get the decoded ID from the span before
decodedId = ( headlines[ i ].previousSibling !== null ) ?
headlines[ i ].previousSibling.id : '',
links = toc.querySelector( "a[href='#" + headlineId + "']" ) ||
toc.querySelector( "a[href='#" + decodedId + "']" ),
targetLink = links.parentNode,
activeLink = toc.querySelector( '.' + ACTIVE_ITEM_CLASS );
if ( activeLink !== null ) {
activeLink.classList.remove( ACTIVE_ITEM_CLASS );
2020-02-15 22:56:29 +00:00
}
if ( targetLink !== null ) {
targetLink.classList.add( ACTIVE_ITEM_CLASS );
2020-02-15 22:56:29 +00:00
}
}
}, {
// Will break in viewport with short height
// But calculating bottom margin on the fly is too costly
rootMargin: marginTop + ' 0px -85% 0px'
} );
observer.observe( headlines[ i ] );
2020-02-15 22:56:29 +00:00
}
2020-02-15 22:55:31 +00:00
}
module.exports = {
init: initToC
};