2019-08-15 17:40:13 +00:00
|
|
|
/*
|
|
|
|
* Citizen - ToC JS
|
|
|
|
* https://starcitizen.tools
|
|
|
|
*/
|
|
|
|
|
2020-06-17 03:16:45 +00:00
|
|
|
/**
|
|
|
|
* Add active HTML class to items in table of content based on user viewport.
|
2020-07-05 21:07:36 +00:00
|
|
|
*
|
2020-06-17 03:16:45 +00:00
|
|
|
* @constructor
|
|
|
|
*/
|
2021-04-02 19:42:56 +00:00
|
|
|
function intersectionHandler() {
|
2021-03-08 20:02:20 +00:00
|
|
|
var sections = document.querySelectorAll( '.mw-headline' ),
|
2021-04-02 19:42:56 +00:00
|
|
|
htmlStyles = window.getComputedStyle( document.documentElement ),
|
|
|
|
scrollPaddingTop = htmlStyles.getPropertyValue( 'scroll-padding-top' ),
|
|
|
|
// Align with scroll offset set in CSS
|
|
|
|
marginTop = "-" + scrollPaddingTop,
|
|
|
|
id, id2, toclink, node, active;
|
|
|
|
|
|
|
|
for (let i = 0; i < sections.length; i++) {
|
|
|
|
const observer = new IntersectionObserver( ( entry ) => {
|
|
|
|
if ( entry[ 0 ].isIntersecting ) {
|
|
|
|
id = sections[i].id;
|
2021-03-14 03:34:15 +00:00
|
|
|
// Try the ID of the span before
|
2021-04-02 19:42:56 +00:00
|
|
|
if ( sections[i].previousSibling !== null ) {
|
|
|
|
id2 = sections[i].previousSibling.id || '';
|
2021-03-14 03:34:15 +00:00
|
|
|
}
|
|
|
|
toclink = document.querySelector( "a[href='#" + id + "']" ) || document.querySelector( "a[href='#" + id2 + "']" );
|
|
|
|
node = toclink.parentNode;
|
2020-02-16 00:20:20 +00:00
|
|
|
active = document.querySelector( '.active' );
|
|
|
|
if ( active !== null ) {
|
|
|
|
active.classList.remove( 'active' );
|
2020-02-15 22:56:29 +00:00
|
|
|
}
|
2020-02-16 00:20:20 +00:00
|
|
|
if ( node !== null ) {
|
|
|
|
node.classList.add( 'active' );
|
2020-02-15 22:56:29 +00:00
|
|
|
}
|
|
|
|
}
|
2021-04-02 19:42:56 +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( sections[i] );
|
2020-02-15 22:56:29 +00:00
|
|
|
}
|
2020-02-15 22:55:31 +00:00
|
|
|
}
|
2019-12-30 14:53:22 +00:00
|
|
|
|
2020-08-12 16:37:43 +00:00
|
|
|
function main() {
|
2021-04-02 19:42:56 +00:00
|
|
|
// Check for has-toc class since it is loaded way before #toc is present
|
|
|
|
if ( document.body.classList.contains( 'skin-citizen-has-toc' ) ) {
|
|
|
|
intersectionHandler();
|
2020-08-12 16:37:43 +00:00
|
|
|
}
|
2020-02-16 00:20:20 +00:00
|
|
|
}
|
2020-08-12 16:37:43 +00:00
|
|
|
|
|
|
|
main();
|