MediaWiki:Common.js

From TechInfoDepot
Jump to navigationJump to search

Note: After saving, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Go to Menu → Settings (Opera → Preferences on a Mac) and then to Privacy & security → Clear browsing data → Cached images and files.
/* Any JavaScript here will be loaded for all users on every page load. */


/**
 * Keep code in MediaWiki:Common.js to a minimum as it is unconditionally
 * loaded for all users on every wiki page. If possible create a gadget that is
 * enabled by default instead of adding it here (since gadgets are fully
 * optimized ResourceLoader modules with possibility to add dependencies etc.)
 *
 * Since Common.js isn't a gadget, there is no place to declare its
 * dependencies, so we have to lazy load them with mw.loader.using on demand and
 * then execute the rest in the callback. In most cases these dependencies will
 * be loaded (or loading) already and the callback will not be delayed. In case a
 * dependency hasn't arrived yet it'll make sure those are loaded before this.
 */



/* importScript('User:DarkShadow/extraeditbuttons.js'); */
/* importScript('User:DarkShadow/HotCat.js'); */


/* global mw, $, importStylesheet, importScript */
/* jshint strict:false, browser:true */

mw.loader.using( ['mediawiki.util', 'mediawiki.notify', 'jquery.client'], function () {
/* Begin of mw.loader.using callback */

/**
 * Main Page layout fixes
 *
 * Description: Adds an additional link to the complete list of languages available.
 * Maintainers: [[User:AzaToth]], [[User:R. Koot]], [[User:Alex Smotrov]]
 */
if ( mw.config.get( 'wgPageName' ) === 'Main_Page' || mw.config.get( 'wgPageName' ) === 'Talk:Main_Page' ) {
    $( function () {
        mw.util.addPortletLink( 'p-lang', '//meta.wikimedia.org/wiki/List_of_Wikipedias',
            'Complete list', 'interwiki-completelist', 'Complete list of Wikipedias' );
    } );
}

/**
 * Redirect User:Name/skin.js and skin.css to the current skin's pages
 * (unless the 'skin' page really exists)
 * @source: http://www.mediawiki.org/wiki/Snippets/Redirect_skin.js
 * @rev: 2
 */
if ( mw.config.get( 'wgArticleId' ) === 0 && mw.config.get( 'wgNamespaceNumber' ) === 2 ) {
    var titleParts = mw.config.get( 'wgPageName' ).split( '/' );
    /* Make sure there was a part before and after the slash
       and that the latter is 'skin.js' or 'skin.css' */
    if ( titleParts.length == 2 ) {
        var userSkinPage = titleParts.shift() + '/' + mw.config.get( 'skin' );
        if ( titleParts.slice( -1 ) == 'skin.js' ) {
            window.location.href = mw.util.getUrl( userSkinPage + '.js' );
        } else if ( titleParts.slice( -1 ) == 'skin.css' ) {
            window.location.href = mw.util.getUrl( userSkinPage + '.css' );
        }
    }
}

/**
 * Map addPortletLink to mw.util
 * @deprecated: Use mw.util.addPortletLink instead.
 */
mw.log.deprecate( window, 'addPortletLink', mw.util.addPortletLink, 'Use mw.util.addPortletLink instead' );

/**
 * Extract a URL parameter from the current URL
 * @deprecated: Use mw.util.getParamValue with proper escaping
 */
mw.log.deprecate( window, 'getURLParamValue', mw.util.getParamValue, 'Use mw.util.getParamValue instead' );

/**
 * Test if an element has a certain class
 * @deprecated:  Use $(element).hasClass() instead.
 */
mw.log.deprecate( window, 'hasClass', function ( element, className ) {
    return $( element ).hasClass( className );
}, 'Use jQuery.hasClass() instead' );

/**
 * @source www.mediawiki.org/wiki/Snippets/Load_JS_and_CSS_by_URL
 * @rev 6
 */
var extraCSS = mw.util.getParamValue( 'withCSS' ),
    extraJS = mw.util.getParamValue( 'withJS' );

if ( extraCSS ) {
    if ( extraCSS.match( /^MediaWiki:[^&<>=%#]*\.css$/ ) ) {
        importStylesheet( extraCSS );
    } else {
        mw.notify( 'Only pages from the MediaWiki namespace are allowed.', { title: 'Invalid withCSS value' } );
    }
}

if ( extraJS ) {
    if ( extraJS.match( /^MediaWiki:[^&<>=%#]*\.js$/ ) ) {
        importScript( extraJS );
    } else {
        mw.notify( 'Only pages from the MediaWiki namespace are allowed.', { title: 'Invalid withJS value' } );
    }
}

/**
 * Import more specific scripts if necessary
 */
if ( mw.config.get( 'wgAction' ) === 'edit' || mw.config.get( 'wgAction' ) === 'submit' || mw.config.get( 'wgCanonicalSpecialPageName' ) === 'Upload' ) {
    /* scripts specific to editing pages */
    importScript( 'MediaWiki:Common.js/edit.js' );
} else if ( mw.config.get( 'wgCanonicalSpecialPageName' ) === 'Watchlist' ) {
    /* watchlist scripts */
    importScript( 'MediaWiki:Common.js/watchlist.js' );
}
if ( mw.config.get( 'wgNamespaceNumber' ) === 6 ) {
    /* file description page scripts */
    importScript( 'MediaWiki:Common.js/file.js' );
}

/**
 * Helper script for .hlist class in Common.css
 * Add pseudo-selector class to last-child list items in IE8
 * @source mediawiki.org/wiki/Snippets/Horizontal_lists
 * @revision 6 (2014-08-23)
 * @author [[User:Edokter]]
 */
( function ( mw, $ ) {
    var profile = $.client.profile();
    if ( profile.name === 'msie' && profile.versionNumber === 8 ) {
        mw.hook( 'wikipage.content' ).add( function ( $content ) {
            $content.find( '.hlist' ).find( 'dd:last-child, dt:last-child, li:last-child' )
                .addClass( 'hlist-last-child' );
        } );
    }
}( mediaWiki, jQuery ) );

/**
 * Fix for Windows XP Unicode font rendering
 */
if ( navigator.appVersion.search(/windows nt 5/i) !== -1 ) {
    mw.util.addCSS( '.IPA { font-family: "Lucida Sans Unicode", "Arial Unicode MS"; } ' +
                '.Unicode { font-family: "Arial Unicode MS", "Lucida Sans Unicode"; } ' );
}

/**
 * WikiMiniAtlas
 *
 * Description: WikiMiniAtlas is a popup click and drag world map.
 *              This script causes all of our coordinate links to display the WikiMiniAtlas popup button.
 *              The script itself is located on meta because it is used by many projects.
 *              See [[Meta:WikiMiniAtlas]] for more information.
 * Maintainers: [[User:Dschwen]]
 */
( function () {
    var require_wikiminiatlas = false;
    var coord_filter = /geohack/;
    $( function () {
        $( 'a.external.text' ).each( function( key, link ) {
            if ( link.href && coord_filter.exec( link.href ) ) {
                require_wikiminiatlas = true;
                // break from loop
                return false;
            }
        } );
        if ( $( 'div.kmldata' ).length ) {
            require_wikiminiatlas = true;
        }
        if ( require_wikiminiatlas ) {
            mw.loader.load( '//meta.wikimedia.org/w/index.php?title=MediaWiki:Wikiminiatlas.js&action=raw&ctype=text/javascript' );
        }
    } );
} )();

	/**
	 * Collapsible tables; reimplemented with mw-collapsible
	 * Styling is also in place to avoid FOUC
	 *
	 * Allows tables to be collapsed, showing only the header. See [[Help:Collapsing]].
	 * @version 3.0.0 (2018-05-20)
	 * @source https://www.mediawiki.org/wiki/MediaWiki:Gadget-collapsibleTables.js
	 * @author [[User:R. Koot]]
	 * @author [[User:Krinkle]]
	 * @author [[User:TheDJ]]
	 * @deprecated Since MediaWiki 1.20: Use class="mw-collapsible" instead which
	 * is supported in MediaWiki core. Shimmable since MediaWiki 1.32
	 *
	 * @param {jQuery} $content
	 */
	function makeCollapsibleMwCollapsible( $content ) {
		var $tables = $content
			.find( 'table.collapsible:not(.mw-collapsible)' )
			.addClass( 'mw-collapsible' );

		$.each( $tables, function ( index, table ) {
			// mw.log.warn( 'This page is using the deprecated class collapsible. Please replace it with mw-collapsible.');
			if ( $( table ).hasClass( 'collapsed' ) ) {
				$( table ).addClass( 'mw-collapsed' );
				// mw.log.warn( 'This page is using the deprecated class collapsed. Please replace it with mw-collapsed.');
			}
		} );
		if ( $tables.length > 0 ) {
			mw.loader.using( 'jquery.makeCollapsible' ).then( function () {
				$tables.makeCollapsible();
			} );
		}
	}
	mw.hook( 'wikipage.content' ).add( makeCollapsibleMwCollapsible );

	/**
	 * Add support to mw-collapsible for autocollapse, innercollapse and outercollapse
	 *
	 * Maintainers: TheDJ
	 */
	function mwCollapsibleSetup( $collapsibleContent ) {
		var $element,
			$toggle,
			autoCollapseThreshold = 2;
		$.each( $collapsibleContent, function ( index, element ) {
			$element = $( element );
			if ( $element.hasClass( 'collapsible' ) ) {
				$element.find( 'tr:first > th:first' ).prepend( $element.find( 'tr:first > * > .mw-collapsible-toggle' ) );
			}
			if ( $collapsibleContent.length >= autoCollapseThreshold && $element.hasClass( 'autocollapse' ) ) {
				$element.data( 'mw-collapsible' ).collapse();
			} else if ( $element.hasClass( 'innercollapse' ) ) {
				if ( $element.parents( '.outercollapse' ).length > 0 ) {
					$element.data( 'mw-collapsible' ).collapse();
				}
			}
			// because of colored backgrounds, style the link in the text color
			// to ensure accessible contrast
			$toggle = $element.find( '.mw-collapsible-toggle' );
			if ( $toggle.length ) {
				// Make the toggle inherit text color
				if ( $toggle.parent()[ 0 ].style.color ) {
					$toggle.find( 'a' ).css( 'color', 'inherit' );
				}
			}
		} );
	}

	mw.hook( 'wikipage.collapsibleContent' ).add( mwCollapsibleSetup );

	/**
	 * Magic editintros ****************************************************
	 *
	 * Description: Adds editintros on disambiguation pages and BLP pages.
	 * Maintainers: [[User:RockMFR]]
	 *
	 * @param {string} name
	 */
	function addEditIntro( name ) {
		$( '.mw-editsection, #ca-edit, #ca-ve-edit' ).find( 'a' ).each( function ( i, el ) {
			el.href = $( this ).attr( 'href' ) + '&editintro=' + name;
		} );
	}

	if ( mw.config.get( 'wgNamespaceNumber' ) === 0 ) {
		$( function () {
			if ( document.getElementById( 'disambigbox' ) ) {
				addEditIntro( 'Template:Disambig_editintro' );
			}
		} );

		$( function () {
			var cats = mw.config.get( 'wgCategories' );
			if ( !cats ) {
				return;
			}
			if ( $.inArray( 'Living people', cats ) !== -1 || $.inArray( 'Possibly living people', cats ) !== -1 ) {
				addEditIntro( 'Template:BLP_editintro' );
			}
		} );
	}
	/* End of mw.loader.using callback */
} );

/* adds show/hide-button to navigation bars */
function createNavigationBarToggleButton() {
    var indexNavigationBar = 0;
    var NavFrame;
    var NavChild;
    /* iterate over all < div >-elements */
    var divs = document.getElementsByTagName( 'div' );
    for ( var i = 0; (NavFrame = divs[i]); i++ ) {
        /* if found a navigation bar */
        if ( $( NavFrame ).hasClass( 'NavFrame' ) ) {

            indexNavigationBar++;
            var NavToggle = document.createElement( 'a' );
            NavToggle.className = 'NavToggle';
            NavToggle.setAttribute( 'id', 'NavToggle' + indexNavigationBar );
            NavToggle.setAttribute( 'href', '#' );
            $( NavToggle ).on( 'click', $.proxy( window.toggleNavigationBar, window, indexNavigationBar ) );

            var isCollapsed = $( NavFrame ).hasClass( 'collapsed' );
            /**
             * Check if any children are already hidden.  This loop is here for backwards compatibility:
             * the old way of making NavFrames start out collapsed was to manually add style="display:none"
             * to all the NavPic/NavContent elements.  Since this was bad for accessibility (no way to make
             * the content visible without JavaScript support), the new recommended way is to add the class
             * "collapsed" to the NavFrame itself, just like with collapsible tables.
             */
            for ( NavChild = NavFrame.firstChild; NavChild != null && !isCollapsed; NavChild = NavChild.nextSibling ) {
                if ( $( NavChild ).hasClass( 'NavPic' ) || $( NavChild ).hasClass( 'NavContent' ) ) {
                    if ( NavChild.style.display === 'none' ) {
                        isCollapsed = true;
                    }
                }
            }
            if ( isCollapsed ) {
                for ( NavChild = NavFrame.firstChild; NavChild != null; NavChild = NavChild.nextSibling ) {
                    if ( $( NavChild ).hasClass( 'NavPic' ) || $( NavChild ).hasClass( 'NavContent' ) ) {
                        NavChild.style.display = 'none';
                    }
                }
            }
            var NavToggleText = document.createTextNode( isCollapsed ? NavigationBarShow : NavigationBarHide );
            NavToggle.appendChild( NavToggleText );

            /* Find the NavHead and attach the toggle link (Must be this complicated because Moz's firstChild handling is borked) */
            for( var j = 0; j < NavFrame.childNodes.length; j++ ) {
                if ( $( NavFrame.childNodes[j] ).hasClass( 'NavHead' ) ) {
                    NavToggle.style.color = NavFrame.childNodes[j].style.color;
                    NavFrame.childNodes[j].appendChild( NavToggle );
                }
            }
            NavFrame.setAttribute( 'id', 'NavFrame' + indexNavigationBar );
        }
    }
}

mw.hook( 'wikipage.content' ).add( createNavigationBarToggleButton );

/**
 * Uploadwizard_newusers
 * Switches in a message for non-autoconfirmed users at [[Wikipedia:Upload]]
 *
 * Maintainers: [[User:Krimpet]]
 */
function uploadwizard_newusers() {
    if ( mw.config.get( 'wgNamespaceNumber' ) === 4 && mw.config.get( 'wgTitle' ) === 'Upload' && mw.config.get( 'wgAction' ) === 'view' ) {
        var oldDiv = document.getElementById( 'autoconfirmedusers' ),
            newDiv = document.getElementById( 'newusers' );
        if ( oldDiv && newDiv ) {
            var userGroups = mw.config.get( 'wgUserGroups' );
            if ( userGroups ) {
                for ( var i = 0; i < userGroups.length; i++ ) {
                    if ( userGroups[i] === 'autoconfirmed' ) {
                        oldDiv.style.display = 'block';
                        newDiv.style.display = 'none';
                        return;
                    }
                }
            }
            oldDiv.style.display = 'none';
            newDiv.style.display = 'block';
            return;
        }
    }
}

$(uploadwizard_newusers);

/**
 * Magic editintros ****************************************************
 *
 * Description: Adds editintros on disambiguation pages and BLP pages.
 * Maintainers: [[User:RockMFR]]
 */
function addEditIntro( name ) {
    $( '.mw-editsection, #ca-edit' ).find( 'a' ).each( function ( i, el ) {
        el.href = $( this ).attr( 'href' ) + '&editintro=' + name;
    } );
}

if ( mw.config.get( 'wgNamespaceNumber' ) === 0 ) {
    $( function () {
        if ( document.getElementById( 'disambigbox' ) ) {
            addEditIntro( 'Template:Disambig_editintro' );
        }
    } );

    $( function () {
        var cats = mw.config.get('wgCategories');
        if ( !cats ) {
            return;
        }
        if ( $.inArray( 'Living people', cats ) !== -1 || $.inArray( 'Possibly living people', cats ) !== -1 ) {
            addEditIntro( 'Template:BLP_editintro' );
        }
    } );
}

/* End of mw.loader.using callback */

/*##############################################*/

/**
 * JS Tab System, jacked and hacked from the jsprefs in wikibits.js
 *
 * Original code by Dantman
 * Refactored a bit by Jack Phoenix on 11 April 2014
 * Support for linking to a particular tab by MatmaRex on 30 December 2016.
 * @note Should be rewritten to properly use jQuery like how mediawiki.special.preferences.js does.
 */
var TabSystem = {
	/**
	 * @property {boolean}
	 * Is the user's browser a KHTML-based one (usually, but not always, Konqueror)?
	 */
	isKHTML: ( navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled ) ),
 
	/**
	 * @property {boolean}
	 * Is the user's browser Opera?
	 */
	isOpera: navigator.userAgent.toLowerCase().indexOf( 'opera' ) != -1,
 
	/*
		Written by Jonathan Snook, http://www.snook.ca/jonathan
		Add-ons by Robert Nyman, http://www.robertnyman.com
		Author says "The credit comment is all it takes, no license. Go crazy with it!:-)"
		From http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
	*/
	getElementsByClassName: function( oElm, strTagName, oClassNames ) {
		var arrReturnElements = [];
		if ( typeof oElm.getElementsByClassName == 'function' ) {
			/* Use a native implementation where possible FF3, Saf3.2, Opera 9.5 */
			var arrNativeReturn = oElm.getElementsByClassName( oClassNames );
			if ( strTagName == '*' ) {
				return arrNativeReturn;
			}
			for ( var h = 0; h < arrNativeReturn.length; h++ ) {
				if ( arrNativeReturn[h].tagName.toLowerCase() == strTagName.toLowerCase() ) {
					arrReturnElements[arrReturnElements.length] = arrNativeReturn[h];
				}
			}
			return arrReturnElements;
		}
 
		var arrElements = ( strTagName == '*' && oElm.all ) ? oElm.all : oElm.getElementsByTagName( strTagName );
		var arrRegExpClassNames = [];
		if ( typeof oClassNames == 'object' ) {
			for ( var i = 0; i < oClassNames.length; i++ ) {
				arrRegExpClassNames[arrRegExpClassNames.length] =
					new RegExp( "(^|\\s)" + oClassNames[i].replace( /\-/g, "\\-" ) + "(\\s|$)" );
			}
		} else {
			arrRegExpClassNames[arrRegExpClassNames.length] =
				new RegExp( "(^|\\s)" + oClassNames.replace( /\-/g, "\\-" ) + "(\\s|$)" );
		}
 
		var oElement;
		var bMatchesAll;
		for ( var j = 0; j < arrElements.length; j++ ) {
			oElement = arrElements[j];
			bMatchesAll = true;
			for ( var k = 0; k < arrRegExpClassNames.length; k++ ) {
				if ( !arrRegExpClassNames[k].test( oElement.className ) ) {
					bMatchesAll = false;
					break;
				}
			}
			if ( bMatchesAll ) {
				arrReturnElements[arrReturnElements.length] = oElement;
			}
		}
 
		return arrReturnElements;
	},
 
	/**
	 * Main function that performs all the magic on all div elements that have
	 * class="tab" and are inside a div that has class="tabcontainer".
	 */
	main: function() {
		var tabcontainers = TabSystem.getElementsByClassName( document, 'div', 'tabcontainer' );
		for ( var tc = 0; tc < tabcontainers.length; tc++ ) {
			if ( !tabcontainers[tc] || !document.createElement ) {
				return;
			}
			if ( tabcontainers[tc].nodeName.toLowerCase() == 'a' ) {
				return; // Occasional IE problem
			}
 
			tabcontainers[tc].className += ' jstabs';
 
			var sections = [];
			var children = tabcontainers[tc].childNodes;
			var seci = 0;
 
			for ( var i = 0; i < children.length; i++ ) {
				if ( children[i].className && children[i].className.match( /tab/i ) ) {
					children[i].id = 'tabsection-' + seci + '-' + tc;
					children[i].className += ' tabsection';
					// Opera and KHTML-based browsers get a special class
					if ( TabSystem.isOpera || TabSystem.isKHTML ) {
						children[i].className += ' tabsection operatabsection';
					}
					var legends = TabSystem.getElementsByClassName( children[i], 'div', 'tab' );
					sections[seci] = {};
					legends[0].className = 'mainTab';
					if ( legends[0] && legends[0].firstChild.nodeValue ) {
						sections[seci].text = legends[0].firstChild.nodeValue;
					} else {
						sections[seci].text = '# ' + seci;
					}
					sections[seci].secid = children[i].id;
					seci++;
					if ( sections.length != 1 ) {
						children[i].style.display = 'none';
					} else {
						var selectedid = children[i].id;
					}
				}
			}
 
			var toc = document.createElement( 'ul' );
			toc.className = 'tabtoc';
			toc.id = 'tabtoc-' + tc;
			toc.selectedid = selectedid;
 
			for ( i = 0; i < sections.length; i++ ) {
				var li = document.createElement( 'li' );
				if ( i === 0 ) {
					li.className = 'selected';
				}
				var a = document.createElement( 'a' );
				a.href = '#' + sections[i].secid;
				a.appendChild( document.createTextNode( sections[i].text ) );
				a.secid = sections[i].secid;
				li.appendChild( a );
				toc.appendChild( li );
				// Capture current value of variables in the closure
				( function ( i, a ) {
					$( window ).on( 'hashchange', function () {
						if ( location.hash === '#' + sections[i].secid ) {
							TabSystem.uncoverTabSection( toc, a );
						}
					} )
					if ( location.hash === '#' + sections[i].secid ) {
						TabSystem.uncoverTabSection( toc, a );
					}
				} )( i, a );
			}
 
			tabcontainers[tc].parentNode.insertBefore( toc, tabcontainers[tc] );
		}
	},
 
	/**
	 * Show the contents of a tab section when the user clicks on the tab.
	 *
	 * @return {boolean} Always false
	 */
	uncoverTabSection: function( ul, a ) {
		var oldsecid = ul.selectedid;
		var newsec = document.getElementById( a.secid );
		if ( oldsecid != a.secid ) {
			document.getElementById( oldsecid ).style.display = 'none';
			newsec.style.display = 'block';
			ul.selectedid = a.secid;
			var lis = ul.getElementsByTagName( 'li' );
			for ( var i = 0; i < lis.length; i++ ) {
				lis[i].className = '';
			}
			a.parentNode.className = 'selected';
		}
		return false;
	}
};
 
// Attach the onload handler using jQuery.
$( function() {
	TabSystem.main();
} );


/* DO NOT ADD CODE BELOW THIS LINE */