MediaWiki:Common.js

in Wikipedia, die vrye ensiklopedie

Let wel: Na die wysiging is dit dalk nodig om u blaaier se kasgeheue te verfris voordat u die veranderinge sal sien:

  • Firefox / Safari: hou Shift en kliek Herlaai, of druk Ctrl-F5 of Ctrl-R (⌘-R op 'n Mac)
  • Google Chrome: Druk Ctrl-Shift-R (⌘-Shift-R op 'n Mac)
  • Internet Explorer / Edge: Hou Ctrl en kliek Refresh, of druk Ctrl-F5
  • Opera: Gaan na Kieslys → Settings (Opera → Preferences op 'n Mac) en dan na Privacy & security → Clear browsing data → Cached images and files.
/**
 * 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.
 */

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

mw.loader.using( [ 'mediawiki.util' ] ).done( function () {
	/* Begin of mw.loader.using callback */

	/**
	 * 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$/ ) ) {
			mw.loader.load( '/w/index.php?title=' + extraCSS + '&action=raw&ctype=text/css', 'text/css' );
		} else {
			mw.notify( 'Only pages from the MediaWiki namespace are allowed.', { title: 'Invalid withCSS value' } );
		}
	}

	if ( extraJS ) {
		if ( extraJS.match( /^MediaWiki:[^&<>=%#]*\.js$/ ) ) {
			mw.loader.load( '/w/index.php?title=' + extraJS + '&action=raw&ctype=text/javascript' );
		} else {
			mw.notify( 'Only pages from the MediaWiki namespace are allowed.', { title: 'Invalid withJS value' } );
		}
	}

	/**
	 * 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.
	 * Note - use of this service is recommended to be replaced with mw:Help:Extension:Kartographer
	 */
	$( function () {
		var requireWikiminiatlas = $( 'a.external.text[href*="geohack"]' ).length || $( 'div.kmldata' ).length;
		if ( requireWikiminiatlas ) {
			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 );

	/**
	 * Dynamic Navigation Bars (experimental)
	 *
	 * Description: See [[Wikipedia:NavFrame]].
	 * Maintainers: UNMAINTAINED
	 */

	var collapseCaption = 'versteek';
	var expandCaption = 'wys';

	// Set up the words in your language
	var navigationBarHide = '[' + collapseCaption + ']';
	var navigationBarShow = '[' + expandCaption + ']';

	/**
	 * Shows and hides content and picture (if available) of navigation bars.
	 *
	 * @param {number} indexNavigationBar The index of navigation bar to be toggled
	 * @param {jQuery.Event} event Event object
	 * @return {boolean}
	 */
	function toggleNavigationBar( indexNavigationBar, event ) {
		var navToggle = document.getElementById( 'NavToggle' + indexNavigationBar );
		var navFrame = document.getElementById( 'NavFrame' + indexNavigationBar );
		var navChild;

		if ( !navFrame || !navToggle ) {
			return false;
		}

		// If shown now
		if ( navToggle.firstChild.data === navigationBarHide ) {
			for ( navChild = navFrame.firstChild; navChild !== null; navChild = navChild.nextSibling ) {
				if ( $( navChild ).hasClass( 'NavContent' ) ) {
					navChild.style.display = 'none';
				}
			}
			navToggle.firstChild.data = navigationBarShow;

		// If hidden now
		} else if ( navToggle.firstChild.data === navigationBarShow ) {
			for ( navChild = navFrame.firstChild; navChild !== null; navChild = navChild.nextSibling ) {
				if ( $( navChild ).hasClass( 'NavContent' ) ) {
					navChild.style.display = 'block';
				}
			}
			navToggle.firstChild.data = navigationBarHide;
		}

		event.preventDefault();
	}

	/**
	 * Adds show/hide-button to navigation bars.
	 *
	 * @param {jQuery} $content
	 */
	function createNavigationBarToggleButton( $content ) {
		var j, navChild, navToggle, navToggleText, isCollapsed,
			indexNavigationBar = 0;
		// Iterate over all < div >-elements
		var $divs = $content.find( 'div.NavFrame:not(.mw-collapsible)' );
		$divs.each( function ( i, navFrame ) {
			indexNavigationBar++;
			navToggle = document.createElement( 'a' );
			navToggle.className = 'NavToggle';
			navToggle.setAttribute( 'id', 'NavToggle' + indexNavigationBar );
			navToggle.setAttribute( 'href', '#' );
			$( navToggle ).on( 'click', $.proxy( toggleNavigationBar, null, indexNavigationBar ) );

			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';
					}
				}
			}
			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 ( 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 );
	
		/* Actions specific to the edit page */
	if ( mw.config.get( 'wgAction' ) === 'edit' || mw.config.get( 'wgAction' ) === 'submit' ) {
		/**
		 * Fix edit summary prompt for undo
		 *
		 *  Fixes the fact that the undo function combined with the "no edit summary prompter"
		 *  complains about missing editsummary, if leaving the edit summary unchanged.
		 *  Added by [[User:Deskana]], code by [[User:Tra]].
		 *  See also [[phab:T10912]].
		 */
		$( function () {
			if ( document.location.search.indexOf( 'undo=' ) !== -1 && document.getElementsByName( 'wpAutoSummary' )[ 0 ] ) {
				document.getElementsByName( 'wpAutoSummary' )[ 0 ].value = '1';
			}
		} );
	}
	
	/* End of mw.loader.using callback */
} );

function insertTagsTo_(tagOpen, tagClose, sampleText, outputid) {
    var txtarea = document.getElementById(outputid);
    if (!txtarea)
        return;

    // IE
    if (document.selection) {
        var theSelection = document.selection.createRange().text;
        if (!theSelection)
            theSelection=sampleText;
        txtarea.focus();
        if (theSelection.charAt(theSelection.length - 1) == " ") { // exclude ending space char, if any
            theSelection = theSelection.substring(0, theSelection.length - 1);
            document.selection.createRange().text = tagOpen + theSelection + tagClose + " ";
        } else {
            document.selection.createRange().text = tagOpen + theSelection + tagClose;
        }

    // Mozilla
    } else if(txtarea.selectionStart || txtarea.selectionStart == '0') {
        var replaced = false;
        var startPos = txtarea.selectionStart;
        var endPos = txtarea.selectionEnd;
        if (endPos-startPos)
            replaced = true;
        var scrollTop = txtarea.scrollTop;
        var myText = (txtarea.value).substring(startPos, endPos);
        if (!myText)
            myText=sampleText;
        if (myText.charAt(myText.length - 1) == " ") { // exclude ending space char, if any
            subst = tagOpen + myText.substring(0, (myText.length - 1)) + tagClose + " ";
        } else {
            subst = tagOpen + myText + tagClose;
        }
        txtarea.value = txtarea.value.substring(0, startPos) + subst +
            txtarea.value.substring(endPos, txtarea.value.length);
        txtarea.focus();
        //set new selection
        if (replaced) {
            var cPos = startPos+(tagOpen.length+myText.length+tagClose.length);
            txtarea.selectionStart = cPos;
            txtarea.selectionEnd = cPos;
        } else {
            txtarea.selectionStart = startPos+tagOpen.length;
            txtarea.selectionEnd = startPos+tagOpen.length+myText.length;
        }
        txtarea.scrollTop = scrollTop;
    }
    // reposition cursor if possible
    if (txtarea.createTextRange)
        txtarea.caretPos = document.selection.createRange().duplicate();
}

/**
 * Autotekst in uploadpagina voor bestanden
 *
 * Script voor Speciaal:Uploaden
 * Maintainers: [[:commons:User:Yonidebest]], [[:commons:User:Dschwen]]
 */
if (mw.config.get('wgCanonicalSpecialPageName') == 'Upload') {
 mw.loader.load( '/w/index.php?title=MediaWiki:Upload.js&action=raw&ctype=text/javascript' );
}

/**
 * Small search keyboard
 *
 * Author: Maciej Jaros [[:pl:User:Nux]]
 * Licence: CC-BY or [http://opensource.org/licenses/gpl-license.php GNU General Public License v2]
 */
if (mw.config.get( 'wgCanonicalSpecialPageName' ) == 'Search'){
    $(addSearchKeyboards);
}

function addSearchKeyboards() {

    if (document.forms.search)
        addSearchKeyboard(document.forms.search);

    if (document.forms.powersearch)
        addSearchKeyboard(document.forms.powersearch);

}

function addSearchKeyboard(searchForm) {
    var searchBoxId = 'lsearchbox';
    if (!searchForm.lsearchbox) {
        if (searchForm.search.id === '') {
            searchBoxId = searchForm.name + 'box';
            searchForm.search.id = searchBoxId;
        } else
            searchBoxId = searchForm.search.id;
    }

    var letters = ['ä', 'å', 'ç', 'è', 'é', 'ë', 'ê', 'ì', 'í', 'ï', 'î', 'ò', 'ó', 'ö', 'ô', 'ß', 'ü', 'û'];
    var html = "Sleutelbord: ";
    for (var i = 0; i < letters.length; i++) {
        html += "<a onclick=\"insertTagsTo_('" + letters[i] + "','','','" + searchBoxId + "');return false\" href=\"#\">" + letters[i] + "</a>";
    }

    var newEl = document.createElement('div');
    newEl.className = 'search_keyboard';
    newEl.innerHTML = html;
    newEl.style.cssText = 'width:50%; font-size:small; font-weight: bold';
    document.getElementById(searchBoxId).parentNode.appendChild(newEl);
}

/** Change Special:Search to use a drop-down menu
 *
 *  Description: Dodaje do strony Special:Search menu selectbox
 *               pozwalające na wybór wyszukiwarki
 *  Created by: [[en:User:Gracenotes]] Updated by [[fr:User:Pmartin]]
 */

if ( mw.config.get( 'wgCanonicalSpecialPageName' ) == 'Search' ) {
    var searchEngines = {
      mediawiki: {
        ShortName: 'MediaWiki Soek',
        Template: "/w/index.php?search={searchTerms}"
      },
      google: {
        ShortName: 'Google',
        Template: "https://www.google.com/search?hl=" + mw.config.get( 'wgUserLanguage' ) + "&q={searchTerms}&as_sitesearch=" + encodeURIComponent( mw.config.get( 'wgServerName' ) )
      },
      wlive: {
        ShortName: 'Bing',
        Template: "https://www.bing.com/search?q={searchTerms}&q1=site:" + encodeURIComponent( mw.config.get( 'wgServerName' ) )
      },

      wikiwix: {
        ShortName: 'Wikiwix',
        Template: "http://www.wikiwix.com/index.php?action={searchTerms}&lang=" + mw.config.get( 'wgContentLanguage' )
      }

    };
    $(externalSearchEngines);
}


function externalSearchEngines() {
  if (typeof SpecialSearchEnhanced2Disabled != 'undefined') return;


  var mainNode = document.getElementById('powersearch');
  if (!mainNode) mainNode = document.getElementById('search');
  if (!mainNode) return;

  var beforeNode = document.getElementById("mw-search-top-table");
  if (!beforeNode) return;
  beforeNode = beforeNode.nextSibling;
  if (!beforeNode) return;

  var firstEngine = 'mediawiki';

  var choices = document.createElement('div');
  choices.setAttribute('id','searchengineChoices');
  choices.style.textAlign = 'center';

  var lsearchbox = document.getElementById('searchText');
  var initValue = lsearchbox.value;

  var space = "";

  for (var id in searchEngines) {
    var engine = searchEngines[id];
if(engine.ShortName)
   {
    if (space) choices.appendChild(space);
    space = document.createTextNode(" ");

    var attr = {
      type: 'radio',
      name: 'searchengineselect',
      value: id,
      onFocus: "changeSearchEngine(this.value)",
      id: "searchengineRadio-"+id
    };

    var html = "<input";
    for (var a in attr) html += " " + a + "='" + attr[a] + "'";
    html += " />";
    var span = document.createElement('span');
    span.innerHTML = html;

    choices.appendChild( span );
    var label;
    if (engine.Template.indexOf('http') === 0) {
      label = document.createElement('a');
      label.href = engine.Template.replace("{searchTerms}", initValue).replace("{language}", 'fr');
    } else {
      label = document.createElement('label');
    }

    label.appendChild( document.createTextNode( engine.ShortName ) );
    choices.appendChild( label );
  }
 }
  mainNode.insertBefore(choices, beforeNode);

  var input = document.createElement('input');
  input.id = 'searchengineextraparam';
  input.type = 'hidden';

  mainNode.insertBefore(input, beforeNode);

  changeSearchEngine(firstEngine, initValue);
}

function changeSearchEngine(selectedId, searchTerms) {

  var currentId = document.getElementById('searchengineChoices').currentChoice;
  if (selectedId == currentId) return;

  document.getElementById('searchengineChoices').currentChoice = selectedId;
  var radio = document.getElementById('searchengineRadio-'  + selectedId);
  radio.checked = 'checked';

  var engine = searchEngines[selectedId];
  var p = engine.Template.indexOf('?');
  var params = engine.Template.substr(p+1);

  var form;
  if (document.forms.search) {
    form = document.forms.search;
  } else {
    form = document.getElementById('powersearch');
  }
  form.setAttribute('action', engine.Template.substr(0,p));

  var l = ("" + params).split("&");
  for (var idx = 0;idx < l.length;idx++) {
    var p = l[idx].split("=");
    var pValue = p[1];

    if (pValue == "{language}") {
    } else if (pValue == "{searchTerms}") {
      var input;
      input = document.getElementById('searchText');

      input.name = p[0];
    } else {
      var input = document.getElementById('searchengineextraparam');

      input.name = p[0];
      input.value = pValue;
    }
  }
}


/*
Plasing van [wysig]-skakel
--------------------------
Correction des titres qui s'affichent mal en raison de limitations dues à MediaWiki.

Copyright 2006, Marc Mongenet. Licence GPL et GFDL.

The function looks for <span class="editsection">, and move them
at the end of their parent and display them inline in small font.
var oldEditsectionLinks=true disables the function.
*/
function setModifySectionStyle() {
  try {
    if ( !(typeof oldEditsectionLinks == 'undefined' || oldEditsectionLinks === false) ){
     return;
    }
    mw.util.addCSS( 'span.editsection { font-size: xx-small; font-weight: normal; float: none;  }' );
    var spans = document.getElementsByTagName( 'span' ), s;
    for ( s = 0; s < spans.length; ++s ) {
      var span = spans[s];
      if ( span.className == 'editsection' ) {
        span.parentNode.appendChild( document.createTextNode(' ') );
        span.parentNode.appendChild( span );
      }
    }
  } catch (e) { /* something went wrong */ }
}
$(setModifySectionStyle);


/**
 * Interwiki links to featured articles ***************************************
 *
 * Description: Highlights interwiki links to featured articles (or
 *              equivalents) by changing the bullet before the interwiki link
 *              into a star.
 * Maintainers: [[User:R. Koot]]
 */
function LinkFA() {
    if ( document.getElementById( 'p-lang' ) ) {
        var InterwikiLinks = document.getElementById( 'p-lang' ).getElementsByTagName( 'li' );

        for ( var i = 0; i < InterwikiLinks.length; i++ ) {
            var className = InterwikiLinks[i].className.match(/interwiki-[-\w]+/);
            if ( document.getElementById( className + '-fa' ) && InterwikiLinks[i].className.indexOf( 'badge-featuredarticle' ) === -1 ) {
                InterwikiLinks[i].className += ' FA';
                InterwikiLinks[i].title = 'Hierdie is ’n voorbladartikel in ’n ander taal.';
            } else if ( document.getElementById( className + '-ga' ) && InterwikiLinks[i].className.indexOf( 'badge-goodarticle' ) === -1 ) {
                InterwikiLinks[i].className += ' GA';
                InterwikiLinks[i].title = 'Hierdie is ’n goeie artikel in ’n ander taal.';
            }
        }
    }
}

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