User:Serhio Magpie/navboxNavigation.js

mw.hook( 'wikipage.content' ).add( function { const items = [];  function forEach ( element, callback ) {    Array.prototype.forEach.call( element, callback );  }  function strToHTML ( element ) {    const node = document.createElement( 'div' );    node.insertAdjacentHTML( 'beforeend', element );    return node.childNodes.length === 1 ? node.firstChild : node.childNodes;  }  function collect ( container ) {    const nodes = container.querySelectorAll( '.navbox' );    forEach( nodes, node => processParentNode( node ) );  }  function processParentNode ( node ) {    const parentItem = processParent( node );    items.push( parentItem );  }  function processParent ( node ) {    const parent = {      container: node,      parentNode: node.parentNode,      linkNodes: node.querySelectorAll( 'a[title^="Шаблон:"]' ),      linkItems: []    };    forEach( parent.linkNodes, node => { const linkItem = processLink( parent, node ); parent.linkItems.push( linkItem ); } );   return parent;  }  function processLink ( parent, node ) {    const linkItem = {      parent: parent,      container: node,      pageName: node.title    };    linkItem.container.addEventListener( 'click', e => { e.preventDefault; getPageContent( linkItem ); } );   return linkItem;  }  function getPageContent ( linkItem ) {    const api = new mw.Api;    const params = {      action: 'parse',      prop: 'text',      formatversion: 2,      page: linkItem.pageName		};    api.get( params ).done( function ( data ) { if( !data ) { return; }     linkItem.pageContent = data.parse.text; linkItem.pageHTML = strToHTML( linkItem.pageContent ) linkItem.templateHTML = linkItem.pageHTML.querySelectorAll( '.navbox' ); replaceParentContent( linkItem ); } ); }  function replaceParentContent ( linkItem ) {    forEach( linkItem.templateHTML, node => { linkItem.parent.parentNode.insertBefore( node, linkItem.parent.container ); processParentNode( node ); } );   linkItem.parent.container.remove;  }  function init  {    const namespace = mw.config.get( 'wgNamespaceNumber' );    if ( namespace === 0 ){      collect( document );    }  }  init; } );