MediaWiki:Gadget-SetGalleryToC.js

From Yugipedia
Jump to: navigation, search

Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: hold down Ctrl and click the Refresh or Reload button. Firefox: hold down ⇧ Shift while clicking Reload (or press Ctrl+⇧ Shift+R). Google Chrome and Safari users can just click the Reload button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.

/**
 * Create a ToC for set galleries (using [[Module:Card collection/modules/Set gallery]]).
 * @author Becasita
 * @contact [[User:Becasita]]
 * TODO: CSS may be unified with version from Card gallery ToC gadget.
 */
( function _gadgetSetGalleryToC( window, $, mw, console ) {
	"use strict";
	var LAST_LOG = '17:59, 31 October 2022 (UTC)';
	function generateToC( $content ) {
		var $tocPlaceholder = $content.find( '.set-gallery__toc' );
		var $contentSectionHeaders = $content.find( '.mw-headline' );
		if ( $contentSectionHeaders.length >= 3 ) { // TODO: make configurable per user?
			var $tocContainer = $( '<div>', {
				'class': 'set-gallery__toc__container'
			} ).appendTo( $tocPlaceholder );
			var $tocList = $( '<ul>' ).appendTo( $tocContainer );
			$contentSectionHeaders.each( function( index, element ) {
				var $sectionTitle = $( element );
				$tocList.append( function() {
					var currentSectionTitleText = $( this )
						.parents( '.set-gallery' )
						.prevAll( 'h2' )
						.first()
						.find( '.mw-headline' )
						.text();
					return $( '<li>', {
						'class': 'set-gallery__toc__entry',
						html: $( currentSectionTitleText === $sectionTitle.text() ? '<strong>' : '<a>', {
							href: '#' + $sectionTitle.attr( 'id' ),
							html: $sectionTitle.html()
						} )
					} );
				} );
			} );
		} else {
			$tocPlaceholder.remove();
		}
	}
	mw.hook( 'wikipage.content' ).add( generateToC );
	console.log( '[Gadget] SetGalleryToC last updated at', LAST_LOG );
} )( window, window.jQuery, window.mediaWiki, window.console );