MediaWiki:Common.js

From Yugipedia
Revision as of 03:38, 25 September 2018 by Corey (talk | contribs)
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.

/*global mw, $, console, enableOldForumEdit */
/*jshint browser:true, curly:false, eqnull:true, strict:false */
mw.loader.using(['mediawiki.util', 'jquery.client'], function () {
/* Begin of mw.loader.using callback */


/**
 * update this (replace the timestamp with 5 tildes) whenever this page is edited
 * this simplifies checking if new code has cleared server caches
 */
var LAST_LOG = '03:38, 25 September 2018 (UTC)';
console.log('MediaWiki:Common.js last updated:', LAST_LOG);

/**
 * Customize wikitext highlither colors.
 */
 window.syntaxHighlighterSiteConfig = {
	wikilinkColor: "#DFEFFF",
	externalLinkColor: "#DFEFFF",
	listOrIndentColor: "#FFDAD0",
	tableColor: "#E8BDF0",
	templateColor: "#EAE4D7",
	parameterColor: "#BAFFBF",
	tagColor: "#FFDAD0",
	entityColor: "#B5C3B5"
};

/**
 * Cleanup excessive space in hlist elements
 */
var items = document.querySelectorAll('.hlist li, .hlist dt, .hlist dd');
for (var i = items.length - 1; i >= 0; i--) {
	items[i].innerHTML = items[i].innerHTML.trim();
}

/**
 * Page format checking
 *
 * Maintainers: [[User:Falzar FZ]]
 */
var mNamespace       = mw.config.get('wgCanonicalNamespace'),
	mNamespaceNumber = mw.config.get('wgNamespaceNumber'),
	mAction          = mw.util.getParamValue('action'),
	mSection         = mw.util.getParamValue('section');

/**
 * Add Template:Navigation if it's not there.
 */
if (
	(mNamespace === 'Card_Rulings' && $('#wpTextbox1').val().indexOf('[\[Category:Group Rulings') === -1) ||
	['Gallery', 'Errata', 'Tips', 'Appearances', 'Trivia', 'Lores', 'Artworks', 'Names', 'Sets']
		.indexOf(mNamespace.replace('Card_', '')) !== -1
) {
	if (!mSection && mAction !== 'submit' && typeof $('#wpTextbox1').val() !== 'undefined') {
		$(addNav);

		function addNav() {
			var vText = $('#wpTextbox1').val()
				.replace('{\{navigation', '{\{Navigation')
				.replace('{\{Navigation2}', '{\{Navigation|mode=nonGame}');
			if (!vText.match('{\{Navigation') && !vText.match('{\{Delete')) {
				$('#wpTextbox1').val('{\{Navigation}}\n\n' + vText);
			} else {
				$('#wpTextbox1').val(vText);
			}

			$('form[name=editform]').submit(function() {
				if ($('#wpTextbox1').val() === '{\{Navigation}}\n\n') {
					alert('You have not made any changes to the template.');
					return false;
				}
			});
		}
	}
}

/**
 * Add Template:Talkheader if it's not there.
 */
if (mNamespaceNumber % 2 === 1 && mNamespaceNumber !== 3 && !mSection && mAction !== 'submit') {
	$(addTalkheader);

	function addTalkheader() {
		var vText = $('#wpTextbox1').val().replace(/{\{[Tt]alkheader/, '{\{Talk header');
		if (!vText.match('{\{Talk header') && !vText.match('{\{Delete')) {
			$('#wpTextbox1').val('{\{Talk header}}\n\n' + vText);
		} else {
			$('#wpTextbox1').val(vText);
		}
	}
}

/**
 * Add a preload depending on the namespace during page creation from redlink.
 */
if (mw.util.getParamValue('redlink')) {
	var vPreloadText = '';
	switch (mNamespace) {
		case 'Card_Tips': // fallthrough
		case 'Card_Trivia': // fallthrough
		case 'Card_Names':
			vPreloadText += '* '; // Deliberate no "\n" at the end.
			break;
		case 'Card_Gallery':
			vPreloadText += '{\{GalleryHeader|lang=en}}\n<gallery widths="175px">\n' +
				'Image.png  | [[Card Number]] ([[Rarity]])<br />\'\'([[Edition]])\'\'<br />[[Set Name]]\n</gallery>\n|}\n\n' +
				'{\{GalleryHeader|lang=jp|set=Anime}}\n<gallery widths="175px">\nImage.png  | [[]]\n</gallery>\n|}\n';
			break;
		case 'Card_Appearances':
			vPreloadText += '* In [[Yu-Gi-Oh! VRAINS - Episode 000|episode 00]], [[character name]] plays this card ' +
				'against [[opponent name]].\n';
			break;
		case 'Card_Errata':
			vPreloadText += '{\{Errata table\n| lore0  = \n| image0 = \n| cap0   = [[Card Number]]<br />' +
				'[[Set Name]]\n\n| lore1  = \n| image1 = \n| cap1   = [[Card Number]]<br />[[Set Name]]\n}}\n';
			break;
		case 'Card_Artworks':
			vPreloadText += '* \n\n{\{ArtworkHeader|lang=jp}}\n<gallery widths="275px">\n' +
				'Image.png  | Japanese\nImage.png  | International\n</gallery>\n|}\n';
			break;
	}
	if (vPreloadText !== '') {
		$(addPreload('{\{Navigation}}\n\n' + vPreloadText));
	}

	function addPreload(pBlankTemplate) {
		$('#wpTextbox1').val(pBlankTemplate);

		$('#wpSave, #wpPreview').mousedown(cleanUpStuff);
		function cleanUpStuff() {
			$('#wpTextbox1').val($('#wpTextbox1').val()
				.replace('{\{Navigation2}}', '{\{Navigation|mode=nonGame}}')
				.replace('{\{Navigation3}}', '{\{Navigation|mode=otherGame}}')
			);
		}

		$('form[name=editform]').submit(function() {
			if ($('#wpTextbox1').val() === pBlankTemplate) {
				alert('You have not made any changes to the template.');
				return false;
			}
		});
	}

}

/**
 * Add missing preload to [[MediaWiki:Createbox-exists]].
 * Using js since there doesn't seem to be a "getURL" option in the wikia magic words.
 * TODO: check if stil needed.
 */
if (mAction === 'create' && $('[name="preload"]').val() === '') {
	$('[name="preload"]').val(mw.util.getParamValue('preload'));
}

/**
 * Remove empty rows from {{Infobox}} transclusions
 */
$('.infobox tr').each(function () {
	if (
		!$.trim($(this).text()) &&
		!$(this).find('img').length &&
		!$(this).find('hr').length
	) {
		$(this).remove();
	}
});

/**
 * Show card details on hover
 * TODO: decide tooltips implementation.
 */
$('.card-link').on('mouseenter', function() {
	if (! document.getElementById('main-card-table')) {
		$(this).find('.card-link-hover-data').load(
			this.getElementsByTagName('a')[0].href + ' #main-card-table', function() {
				$(this).find('.chronology').remove();
			}
		);
	}
});
$('.card-link').on('mouseleave', function() {
	$('.card-link-hover-data').html('');
});


/**
 * The following code is currently maintained by [[User:Becasita]].
 * Contact [[User talk:Becasita]] if the need arises.
 */
( function( window, $, mw ) {

	/**
	 * Fix Special:Ask table headers when wikilinked.
	 * Address to «.JS-changed» to find what elements were changed/created.
	 */
	$( function _specialAskLabelsLinks() {
		if ( mw.config.get( 'wgPageName' ).split( /\s*\/\s*/ )[ 0 ] === 'Special:Ask' ) {
			$( '.smwtable' ).find( 'th' ).each( function( i, el ) {
				$( el ).html( function() {
					return $( this ).text().replace( /\[\[(.*?)]]/g, $( '<a>', {
						class: 'JS-changed',
						href: 'wiki/$1',
						text: '$1'
					} ).prop( 'outerHTML' ) );
				} );
			} );
		}
	} );
	/** End. */

	/**
	 * Fix tabbers labels achors.
	 */
	$(function _fixTabAnchors() {
		// Wait for the tabbers to load:
		mw.loader.using( 'ext.tabber' ).then( function() {

			mw.log( 'DEBUG: Tabbers loaded!' );
			$( '.tabbernav' ).each( function( i, el ) {

				const $el = $( el );
				const $parent = $el.parent();

				// Gets the tab content, given a tab label:
				const getTab = function( $li ) {
					return $parent.find( '.tabbertab' ).filter( function() {
						return this.title.trim() === $li.find( 'a' ).attr( 'title' ).trim();
					});
				};

				// Remove the default click event:
				$el.off( 'click' );

				// Create new click event
				$el.children().click( function( e ) {
					e.preventDefault();

					// Current tab:
					const $currentLabel = $el.find( '.tabberactive' );
					const $currentContent = getTab( $currentLabel );

					// New tab:
					const $newLabel = $( this );
					const $newContent = getTab( $newLabel );

					// Switch tabs:
					$currentLabel.removeClass( 'tabberactive' );
					$newLabel.addClass( 'tabberactive' );
					$currentContent.hide();
					$newContent.show();
				} );

			} );

		} );
	} );
	/** End. */

	/**
	 * Create a ToC for card galleries (using [[Module:Card gallery]]).
	 */
	$( function _addTocToCardGalleries() {
		function generateToC( $content ) {
			mw.log( 'Firing generateToC on: ', $content );

			var $toc = $content.find( '.card-gallery__toc' ).find( 'ul' );
			$content.find( '.mw-headline' ).each( function( index, element ) {
				var $section = $( element );
				$toc.append( function() {
					var sectionText = $( this ).parent().parent().find( 'h2' ).text();
					return $( '<li>', {
						class: 'card-gallery__toc__entry',
						html: $( sectionText === $section.text() ? '<strong>' : '<a>', {
							href: '#' + $section.attr( 'id' ),
							text: $section.text()
						} )
					} );
				} );
			} );
		}

		mw.hook( 'wikipage.content' ).add( generateToC );
	} );
	/** End. */

 	/**
 	 * Links for image uploads on galleries.
 	 */ 
	$(function _linkEmptyGalleries() {
		// Function to link the empty galleries to the upload page:
		function linkEmptyGalleries( $content ) {
			mw.log( 'Firing linkEmptyGalleries on: ', $content );

			$content.find( '.thumb' ).each( function() {
				var $this = $( this );
				if ( !$this.children().length ) {
					// Is an empty gallery box.
					var text = $this.text();
					$this.text( '' );
					$this.append(
						$( '<a>', {
							class: 'noFile',
							href: '/index.php?title=Special:Upload&wpDestFile=' + text,
							text: text
						} )
					);
				}
			} );
		}

		mw.hook( 'wikipage.content' ).add( linkEmptyGalleries );
	} );
	/** End. */
	
	/**
	 * Styles for the edit textbox after wikitext highlight kicks in.
	 */
	mw.hook( 'wikipage.editform' ).add( function( $editform ) {
		var times = 0;
		var interval = window.setInterval(function() {
			if ( mw.loader.getState( 'ext.gadget.DotsSyntaxHighlighter' ) === 'ready' ) {
				mw.log( '[DotsSyntaxHighlighter styles] - modifing' );
				$editform.find( '#wpTextbox0, #wpTextbox1' )
					.css( {
						'border': 'unset',
						'line-height': '1.5em',
						'height': 'unset',
					} )
				;
				window.clearInterval( interval );
				mw.log( '[DotsSyntaxHighlighter styles] - clearing' );
				return;
			}

			if ( times > 10 ) {
				window.clearInterval( interval );
				mw.log( '[DotsSyntaxHighlighter styles] - clearing' );
				return;
			}
		}, 250 );
	} );
	
	/**
	 * Automatically add alt attributes to thumbnail images using the image's caption.
	 */
	$('.thumbinner').each(function(){
		var attr = $(this).find('img').attr('alt');

		if (typeof attr !== typeof undefined && attr !== false) {
			var caption = $(this).find('.thumbcaption').text();
			$(this).find('img').attr('alt', caption);
		}
	});
	
	/** End. */

} )( window, window.jQuery, window.mediaWiki );

/* End of mw.loader.using callback; DO NOT ADD CODE BELOW THIS LINE */
});