Wp/nod/MediaWiki:Common.js

< Wp‎ | nod
Wp > nod > MediaWiki:Common.js

//

mw.loader.using( ['mediawiki.util', 'jquery.client'], function () {

/* แก้ไข/เพิ่มโค้ดด้านล่างนี้ */

/**
 * Redirect User:Name/skin.js and skin.css to the current skin's pages
 * (unless the 'skin' page really exists)
 * @source: //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' );
		}
	}
}

/** Preview before save changes *************************************************************
 *
 *  Description: Force IP to preview before saving changes.
 *               Copyright Marc Mongenet, 2006. Modified by Jutiphan to apply only article namespace
 *  Maintainers: [[User:Jutiphan]]
 *  Source [[mediawiki:Manual:Force preview]]
 */
var permittedGroups = ["user"];

function forcePreview()
{
  if( mw.config.get('wgAction') != "edit") return;
  if( mw.config.get('wgUserGroups') === null) {
    mw.config.get('wgUserGroups') = [];
  }
  if ( mw.config.get( "wgUserGroups" ).filter(function(group) {
    return permittedGroups.indexOf(group) > -1;
  }).length ) return;
  var saveButton = document.getElementById("wpSave");
  if( !saveButton )
    return;
  saveButton.disabled = true;
  saveButton.value = "บันทึกการแก้ไข (กดแสดงตัวอย่างเพื่อตรวจสอบความถูกต้องก่อนบันทึก)";
  saveButton.style.fontWeight = "normal";
  document.getElementById("wpPreview").style.fontWeight = "bold";
}

$(forcePreview);

/** 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 = "บทความนี้เป็นบทความคัดสรรในภาษาอื่น";
            } else if ( document.getElementById( className + '-ga' ) && InterwikiLinks[i].className.indexOf( 'badge-goodarticle' ) === -1 ) {
                InterwikiLinks[i].className += " GA";
                InterwikiLinks[i].title = "บทความนี้เป็นบทความคุณภาพในภาษาอื่น";
            }
        }
    }
}
 
mw.hook( 'wikipage.content' ).add( LinkFA );

/*
Caractères spéciaux
-------------------

Ajouter un menu pour choisir des sous-ensembles de caractères spéciaux.
Ecrit par Zelda, voir sur [[Utilisateur:Zelda/Edittools.js]].
Remplace l'ancienne fonction par une variante plus rapide.
*/

/**
 * Ajoute un menu déroulant permettant de choisir un jeu de caractères spéciaux
 * Les caractères spéciaux sont définis dans Mediawiki:Edittools
 */
function addCharSubsetMenu() {
  var specialchars = document.getElementById('specialcharsets');
  if (!specialchars) return;

  // Construction du menu de selection
  var charSubsetSelect = document.createElement("select");
  charSubsetSelect.setAttribute("style", "display:inline");
  charSubsetSelect.onchange = function () {
    chooseCharSubset(this.selectedIndex);
  };

  // Ajout des options au menu
  var p = document.getElementById('specialcharsets').getElementsByTagName('p');
  for (var i = 0; i < p.length; i++) {
    var opt = document.createElement("option");
    var txt = document.createTextNode(p[i].title);
    opt.appendChild(txt);
    charSubsetSelect.appendChild(opt);
  }

  specialchars.insertBefore(charSubsetSelect, specialchars.childNodes[0]);

  /* default subset - try to use a cookie some day */
  chooseCharSubset(0);
}

/**
 * Affichage du jeu de caractères sélectionné
 */
function chooseCharSubset(index) {
  var p = document.getElementById('specialcharsets').getElementsByTagName('p');
  for (var i = 0; i < p.length; i++) {
    // Initialisation du jeu de caractères sélectionné
    if (i == index) {
      initializeCharSubset(p[i]);
    }
    // Affichage du jeu sélectionné, masquage des autres
    p[i].style.display = i == index ? 'inline' : 'none';
    p[i].style.visibility = i == index ? 'visible' : 'hidden';
  }
}

/**
 * Initialisation du jeu de caractères sélectionné
 * Paramètre : paragraphe contenant le jeu à initialiser. Initialise tous les
 * caractères contenus dans les sous-spans du paragraphe
 */
function initializeCharSubset(p) {
  // recherche des sous-elements de type span à traiter
  var spans = p.getElementsByTagName("span");
  if (!spans) return;

  // regexp pour echapper les caractères JS spéciaux : \ et '
  var re = new RegExp("(\\\\|')", "g");
  // gestion du caractère d'échappement '\'
  var escapeRe = new RegExp("[^\\\\](\\\\\\\\)*\\\\$", "g");
  var unescapeRe = new RegExp("\\\\\\\\", "g");

  // traitement des spans du paragraphe
  for (var j = 0; j < spans.length; j++) {
    // span deja traité
    if (spans[j].childNodes.length == 0 || spans[j].childNodes[0].nodeType != 3) continue;

    // On parse le contenu du span
    var chars = spans[j].childNodes[0].nodeValue.split(" ");
    for (var k = 0; k < chars.length; k++) {
      var a = document.createElement("a");
      var tags = chars[k];

      // regroupement des mots se terminant par un espace protégé par un \
      while (k < chars.length && chars[k].match(escapeRe)) {
        k++;
        tags = tags.substr(0, tags.length - 1) + " " + chars[k];
      }

      // création du lien insertTag(tagBegin, tagEnd, defaultValue) en protegeant les caractères JS \ et '
      tags = (tags.replace(unescapeRe, "\\")).split("+");
      var tagBegin = tags[0].replace(re, "\\$1");
      var tagEnd = tags.length > 1 ? tags[1].replace(re, "\\$1") : "";
      var defaultValue = tags.length > 2 ? tags[2].replace(re, "\\$1") : "";
      a.href = "javascript:insertTags('" + tagBegin + "','" + tagEnd + "', '" + defaultValue + "')";
      //a.href="#";
      //eval("a.onclick = function() { insertTags('" + tagBegin + "','" + tagEnd + "', '" + defaultValue + "'); return false; }");

      a.appendChild(document.createTextNode((tagBegin + tagEnd).replace(unescapeRe, "\\")));
      spans[j].appendChild(a);
      spans[j].appendChild(document.createTextNode(" "));
    }
    // suppression de l'ancien contenu
    spans[j].removeChild(spans[j].firstChild);
  }
}

$(addCharSubsetMenu);

/**
 * Permet d'ajouter d'un jeu de caractères spéciaux dans le menu déroulant
 * paramètres :
 * - nom du jeu de caractères
 * - contenu HTML. Les caractères spéciaux doivent être dans des spans
 *   exemple : "caractères : <span>â ê î ô û</span>"
 */
function addSpecialCharsetHTML(title, charsHTML) {
  var specialchars = document.getElementById('specialcharsets');
  if (!specialchars) return;

  // Ajout d'un nouvel item au menu déroulant
  var select = specialchars.getElementsByTagName("select")[0];
  var opt = document.createElement("option");
  opt.appendChild(document.createTextNode(title));
  select.appendChild(opt);

  // Ajout des caractères spéciaux. Les liens seront initialisé par initializeCharSubset()
  // lors de la sélection
  var specialcharsets = document.getElementById('specialcharsets');
  var p = document.createElement("p");
  p.style.display = "none";
  p.innerHTML = charsHTML;
  specialcharsets.appendChild(p);
}

/**
 * Permet d'ajouter d'un jeu de caractères spéciaux dans le menu déroulant
 * paramètres :
 * - nom du jeu de caractères
 * - caractères spéciaux
 * exemple d'utilisation : addSpecialCharset("Français", "â ê î ô û");
 */
function addSpecialCharset(title, chars) {
  addSpecialCharsetHTML(title, "<span>" + chars + "</span>");
}

/**
 * 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' ) === 'หน้าหลัก') {
    $( document ).ready( function () {
        mw.util.addPortletLink( 'p-lang', '//meta.wikimedia.org/wiki/List_of_Wikipedias',
            'ทุกภาษา', 'interwiki-completelist', 'รายชื่อวิกิพีเดียทุกภาษา' );
    } );
}

/* เริ่มคำสั่งที่จะทำให้ แม่แบบ:Metabox ทำงาน */
/*
 สร้างโดย: [[:ca:Usuari:Peleguer]]
*/
importScript('MediaWiki:Common.js/metabox.js');

/**
 * @source www.mediawiki.org/wiki/Snippets/Load_JS_and_CSS_by_URL
 * @rev 5
 */
// CSS
var extraCSS = mw.util.getParamValue( 'withCSS' );
if ( extraCSS ) {
	if ( extraCSS.match( /^MediaWiki:[^&<>=%#]*\.css$/ ) ) {
		importStylesheet( extraCSS );
	} else {
		mw.notify( 'Only pages from the MediaWiki namespace are allowed.', { title: 'Invalid withCSS value' } );
	}
}
 
// JS
var extraJS = mw.util.getParamValue( 'withJS' );
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') { //scripts specific to editing pages
    importScript('MediaWiki:Common.js/edit.js');
}else if(mw.config.get( 'wgCanonicalSpecialPageName' ) === 'Watchlist'){
    importScript( 'MediaWiki:Common.js/watchlist.js' );
}else if ( mw.config.get( 'wgNamespaceNumber' ) === 4 && mw.config.get( 'wgTitle' ) === 'อัปโหลด' && mw.config.get( 'wgAction' ) === 'view' ) {
   /**
    * Uploadwizard_newusers
    * Switches in a message for non-autoconfirmed users at [[Wikipedia:Upload]]
    *
    * Maintainers: [[User:Krimpet]]
    */
    importScript('MediaWiki:Common.js/uploadWizard.js');
}

/* Fixes for Windows XP 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]]
	 * @added by [[User:Jutiphan]]
	 * @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 = 'ซ่อน';
	var expandCaption = 'แสดง';

	// 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 );

/**
 * Description: Stay on the secure server as much as possible
 * Maintainers: [[User:TheDJ]]
 */
if ( document.location && document.location.protocol === 'https:' ) {
    /* New secure servers */
    mw.loader.load("//en.wikipedia.org/w/index.php?title=MediaWiki:Common.js/secure new.js&action=raw&ctype=text/javascript");
}

// Results from Wikidata
// [[File:Wdsearch_script_screenshot.png]]
if ( mw.config.get( 'wgCanonicalSpecialPageName' ) === 'Search' ||  ( mw.config.get( 'wgArticleId' ) === 0 && mw.config.get( 'wgCanonicalSpecialPageName' ) === false ) ) {
    mw.loader.load("//en.wikipedia.org/w/index.php?title=MediaWiki:Wdsearch.js&action=raw&ctype=text/javascript");
}

/* แก้ไข/เพิ่มโค้ดข้างบนนี้ */
});
//