User:Jitrixis/nameGuzzler.js

From Wikidata
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Note: After publishing, 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)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/**********************************************************************************
***********************************************************************************
**                                      _____               _                    **
**                                     / ____|             | |                   **
**          _ __   __ _ _ __ ___   ___| |  __ _   _ _______| | ___ _ __          **
**         | '_ \ / _` | '_ ` _ \ / _ \ | |_ | | | |_  /_  / |/ _ \ '__|         **
**         | | | | (_| | | | | | |  __/ |__| | |_| |/ / / /| |  __/ |            **
**         |_| |_|\__,_|_| |_| |_|\___|\_____|\__,_/___/___|_|\___|_|            **
**                                                                               **
**                                                                               **
** ----------------------------------------------------------------------------- **
**  How to use :                                                                 **
**   Add to your common.js [[Special:MyPage/common.js]],                         **
**   importScript( 'User:Jitrixis/nameGuzzler.js' );                             **
**                                                                               **
**  Links :                                                                      **
**    [[User:Jitrixis/nameGuzzler.js]]                                           **
**    [[User talk:Jitrixis/nameGuzzler.js]]                                      **
**                                                                               **
**  An idea from [[d:User:Ljubinka]]                                              **
**                                                                               **
**  Read me :                                                                    **
**   This script allows you to insert the same label or aliases in many          **
**   languages at once.                                                          **
**                                                                               **
**  Tips and Tricks :                                                            **
**   There is an autocheck that you can customize in which you would set a range **
**   of language of your choice (eg. Latin alphabet languages, Cyrillic alphabet **
**   languages)                                                                  **
**   go on [[Special:MyPage/nameGuzzlerOption.js]] and add the two lines below:  **
**                                                                               **
**   var nameGuzzler = ["en","de","fr","it", "es", "..."];                       **
**   $(document).myPlugin(nameGuzzler);                                          **
**                                                                               **
***********************************************************************************
**********************************************************************************/
mw.loader.using('mediawiki.api').then(function() {
( function ( mw, $ ) {
	var api = new mw.Api();

	/*
	** Return item Number.
	*/
	var itemId = mw.config.get( 'wbEntityId' );
	if ( !itemId ) {
		return;
	}

	/*
	** Get default label
	*/
	if(typeof nameGuzzler == "undefined")
		var nameGuzzler = ["en","br","co","da","de","es","fr","id","it","nds","nl","pt","ro","sv","ty"];
	importScript( 'User:' + mw.config.get( 'wgUserName' ) + '/nameGuzzlerOption.js' );
	$.fn.myPlugin = function(options) {
        	nameGuzzler = options;
    	};
 
	/*
	** Localized message.
	*/
	var i18n = {
		'en': {
			'title': 'VIP\'s labels',
			'label': 'Labels',
			'languages': 'Languages',
			'send': 'Send',
			'close': 'Close',
			'select-all': 'Select All',
			'auto': 'Auto Select',
			'reset': 'Reset',
			'selected-language': 'selected language(s)',
			'exemple': 'William Shakespeare', // The main writer of a country
			'mode-label': 'Mode Label',
			'mode-aliases': 'Mode Aliases'
		},
		'fr': {
			'title': 'Libellé de VIP',
			'label': 'Libellé',
			'languages': 'Langages',
			'send': 'Envoyer',
			'close': 'Fermer',
			'select-all': 'Tout selectionner',
			'auto': 'Selection auto',
			'reset': 'Reset',
			'selected-language': 'langue(s) selectionnée(s)',
			'exemple': 'Jean-Baptiste Poquelin',
			'mode-label': 'Mode Label',
			'mode-aliases': 'Mode Alias'
		},
		'nl': {
			'title': 'VIP\'s labels',
			'label': 'Labels',
			'languages': 'Talen',
			'send': 'Versturen',
			'close': 'Sluiten',
			'select-all': 'Alles selecteren',
			'auto': 'Automatische selectie',
			'reset': 'Reset',
			'selected-language': 'geselecteerde taal/talen',
			'exemple': 'Louis Couperus'
		},
		'de': {
			'title': 'VIP-Bezeichnungen',
			'label': 'Bezeichnung',
			'languages': 'Sprachen',
			'send': 'Speichern',
			'close': 'Schließen',
			'select-all': 'alle auswählen',
			'auto': 'automatisch auswählen',
			'reset': 'Auswahl zurücksetzen',
			'selected-language': 'ausgewählte Sprache(n)',
			'exemple': 'Johann Wolfgang von Goethe'
		},
		'es': {
			'title': 'Etiquetas VIP',
			'label': 'Etiquetas',
			'languages': 'Idiomas',
			'send': 'Enviar',
			'close': 'Cerrar',
			'select-all': 'Seleccionar todo',
			'auto': 'Selección automática',
			'reset': 'Reiniciar',
			'selected-language': 'idioma(s) seleccionado(s)',
			'exemple': 'Miguel de Cervantes',
			'mode-label': 'Modo etiquetas',
			'mode-aliases': 'Modo alias'
		},
		'it': {
			'title': 'VIP\'s labels',
			'label': 'Etichette',
			'languages': 'Lingue',
			'send': 'Invia',
			'close': 'Chiudi',
			'select-all': 'Seleziona tutto',
			'auto': 'Selezione automatica',
			'reset': 'Reset',
			'selected-language': 'seleziona lingua/e',
			'exemple': 'Dante Alighieri'
		},
        'el': {
			'τίτλος': 'Ετικέτες VIP',
			'label': 'Ετικέτες',
			'languages': 'Γλώσσες',
			'send': 'Αποστολή',
			'close': 'Κλείσιμο',
			'select-all': 'Επιλογή όλων',
			'auto': 'Αυτόματη επιλογή',
			'reset': 'Επαναφορά',
			'selected-language': 'επιλεγμένη/ες γλώσσα/ες',
			'exemple': 'Ουίλλιαμ Σαίξπηρ', // Οおみくろん κύριος συγγραφέας μιας χώρας
			'mode-label': 'Περισσότερες Ετικέττες',
			'mode-aliases': 'Περισσότερα Αλλώνυμα'
		},
		'br': {
			'title': 'Skridennad VIP',
			'label': 'Skridennad',
			'languages': 'Yezhoù',
			'send': 'Degas',
			'close': 'Serriñ',
			'select-all': 'Dibab pep tra',
			'auto': 'Dibab emgefre',
			'reset': 'Adderaouekaat',
			'selected-language': 'yezh(où) dibabet',
			'exemple': 'Añjela Duval',
			'mode-label': 'Mod skridennad',
			'mode-aliases': 'Mod anvet ivez'
		},
		'sv': {
			'title': 'VIP-etiketter',
			'label': 'Etiketter',
			'languages': 'Språk',
			'send': 'Skicka',
			'close': 'Stäng',
			'select-all': 'Välj alla',
			'auto': 'Välj automatiskt',
			'reset': 'Återställ',
			'selected-language': 'valda språk',
			'exemple': 'Astrid Lindgren', // The main writer of a country
			'mode-label': 'Mode-etikett',
			'mode-aliases': 'Mode-alias'
		},
		'ru': {
			'title': 'Обозначения (VIP)',
			'label': 'Обозначения',
			'languages': 'Языки',
			'send': 'Отправить',
			'close': 'Закрыть',
			'select-all': 'Выбрать ВСЁ',
			'auto': 'Автовыбор',
			'reset': 'Сбросить',
			'selected-language': 'избранных языков',
			'exemple': 'Александр Пушкин', // главный писатель страны
			'mode-label': 'Режим обозначений',
			'mode-aliases': 'Режим синонимов'
		},
	};
 
	/*
	** Check if main language can be translated.
	*/
	var lang = mw.config.get( 'wgUserLanguage' );
	if ( ! i18n.hasOwnProperty( lang ) ) {
		lang = 'en';
	}
 
	/*
	** Return localized message.
	*/
	function translate( key ) {
		if ( i18n[ lang ].hasOwnProperty( key ) ) {
			return i18n[ lang ][ key ];
		} else {
			return i18n[ 'en' ][ key ];
		}
	}

	/*
	** Language list
	*/

	var langlist = ["aa", "ab", "ace", "ady", "ady-cyrl", "aeb", "aeb-arab", "aeb-latn", "af", "ak", "aln", "am", "an", "ang", "anp", "ar", "arc", "arn", "arq", "ary", "arz", "as", "ast", "atj", "awa", "av", "avk", "ay", "az", "azb", "ba", "ban", "bar", "bbc", "bbc-latn", "bcc", "bcl", "be", "be-tarask", "bg", "bgn", "bho", "bi", "bjn", "bm", "bn", "bo", "bpy", "bqi", "br", "brh", "bs", "bto", "bug", "bxr", "ca", "cbk-zam", "cdo", "ce", "ceb", "ch", "cho", "chr", "chy", "ckb", "co", "cps", "cr", "crh-latn", "crh-cyrl", "cs", "csb", "cu", "cv", "cy", "da", "dag", "de", "de-at", "de-ch", "din", "diq", "dsb", "dtp", "dty", "dv", "dz", "ee", "egl", "el", "eml", "en", "en-ca", "en-gb", "eo", "es", "et", "eu", "ext", "fa", "ff", "fi", "fit", "fj", "fo", "fr", "frc", "frp", "frr", "fur", "fy", "ga", "gag", "gan", "gan-hans", "gan-hant", "gd", "gl", "glk", "gn", "gom", "gom-deva", "gom-latn", "gor", "got", "grc", "gsw", "gu", "gv", "ha", "hak", "haw", "he", "hi", "hif", "hif-latn", "hil", "ho", "hr", "hrx", "hsb", "ht", "hu", "hy", "hz", "ia", "id", "ie", "ig", "ii", "ik", "ike-cans", "ike-latn", "ilo", "inh", "io", "is", "it", "iu", "ja", "jam", "jbo", "jut", "jv", "ka", "kaa", "kab", "kbd", "kbd-cyrl", "kbp", "kea", "kg", "khw", "ki", "kiu", "kj", "kk", "kk-arab", "kk-cyrl", "kk-latn", "kk-cn", "kk-kz", "kk-tr", "kl", "km", "kn", "ko", "ko-kp", "koi", "kr", "krc", "kri", "krj", "krl", "ks", "ks-arab", "ks-deva", "ksh", "ku", "ku-latn", "ku-arab", "kv", "kw", "ky", "la", "lad", "lb", "lbe", "lez", "lfn", "lg", "li", "lij", "liv", "lki", "lld", "lmo", "ln", "lo", "loz", "lrc", "lt", "ltg", "lus", "luz", "lv", "lzh", "lzz", "mai", "map-bms", "mdf", "mg", "mh", "mhr", "mi", "min", "mk", "ml", "mn", "mo", "mr", "mrj", "ms", "mt", "mus", "mwl", "my", "myv", "mzn", "na", "nah", "nan", "nap", "nb", "nds", "nds-nl", "ne", "new", "ng", "niu", "nl", "nn", "nod", "nov", "nrm", "nso", "nv", "ny", "nys", "oc", "olo", "om", "or", "os", "ota", "pa", "pag", "pam", "pap", "pcd", "pdc", "pdt", "pfl", "pi", "pih", "pl", "pms", "pnb", "pnt", "prg", "ps", "pt", "pt-br", "qu", "qug", "rgn", "rif", "rm", "rmy", "rn", "ro", "roa-tara", "ru", "rue", "rup", "ruq", "ruq-cyrl", "ruq-latn", "rw", "rwr", "sa", "sah", "sat", "sc", "scn", "sco", "sd", "sdc", "sdh", "se", "sei", "ses", "sg", "sgs", "sh", "shi", "shi-tfng", "shi-latn", "shn", "si", "sje", "sk", "sl", "sli", "sm", "sma", "smj", "sn", "so", "sq", "sr", "sr-ec", "sr-el", "srn", "srq", "ss", "st", "stq", "su", "sv", "sw", "szl", "ta", "tcy", "te", "tet", "tg", "tg-cyrl", "tg-latn", "th", "ti", "tk", "tl", "tly", "tn", "to", "tpi", "tr", "tru", "ts", "tt", "tt-cyrl", "tt-latn", "tum", "tw", "ty", "tyv", "udm", "ug", "ug-arab", "ug-latn", "uk", "ur", "uz", "ve", "vec", "vep", "vi", "vls", "vmf", "vo", "vot", "vro", "wa", "war", "wo", "wuu", "xal", "xh", "xmf", "yi", "yo", "yue", "za", "zea", "zh", "zh-cn", "zh-hans", "zh-hant", "zh-hk", "zh-mo", "zh-my", "zh-sg", "zh-tw", "zu"];

	/*
	** Action Lock
	*/
 
	var lock = false;

	/*
	** List all full labels
	*/
 
	var fullLabels = [];
	
	/*
	** Dialog and link
	*/
	function labelLister() {
		var langname = mw.config.get('wgULSLanguages') || {};
		var n = 0;
		var languagetable = "<table>";
		for(var i = 0; i <= 37; i++){
			languagetable += "<tr>";
			for(var j= 0; j <= 10; j++, n++){
				if(typeof langlist[n] != "undefined"){
					var langtitle;
					if(typeof langname[langlist[n]] == "undefined"){
						if(typeof langname[langlist[n].split("-")[0]] == "undefined"){
							langtitle = "";
						}else{
							langtitle = langname[langlist[n].split("-")[0]];
						}
					}else{
						langtitle = langname[langlist[n]];
					}
					languagetable += "<td>";
					languagetable += '<input type="checkbox" name="' + langlist[n] + '" id="' + langlist[n] + '" class="checkbox nameform counting"><label for="' + langlist[n] + '" title="' + langtitle + '" id="' + langlist[n] + '-label" class="counting">' + langlist[n] + '</label>';
					languagetable += "</td>";
				}
			}
			languagetable += "</tr>";
		}
		languagetable += "</table>";
		mw.loader.using( ['jquery.ui'], function () {
			var formFind, messageFind;
			formFind = '<div id="nameGuzzler" title=""><form id="editForm"><div style="text-align:center;width:100%"><label for="label">' + translate( 'label' ) + '&nbsp;:&nbsp;</label><input class="label nameform" id="label" name="label" type="text" placeholder="' + translate( 'exemple' ) + '" style="width: 70%" /></div><div style="text-align:center;width:100%"><label><input type="radio" id="mode-label" name="mode" checked> ' + translate( 'mode-label' ) + ' </label><label><input type="radio" id="mode-aliases" name="mode"> ' + translate( 'mode-aliases' ) + ' </label></div><fieldset><legend>' + translate( 'languages' ) + '&nbsp;:</legend><div style="text-align:right;font-size:0.8em; width:100%"><div style="float:left"><span id="counter">0</span>&nbsp;' + translate( 'selected-language' ) + '</div><a id="reset" class="counting" style="cursor:pointer;padding-right: 10px;">' + translate( 'reset' ) + '</a><a id="auto" class="counting" style="cursor:pointer;padding-left: 10px; padding-right: 10px;">' + translate( 'auto' ) + '</a><a id="select" class="counting" style="cursor:pointer;padding-left: 10px;">' + translate( 'select-all' ) + '</a></div><div style="height:400px;overflow:auto;font-size:0.8em;">' + languagetable + '</div></fieldset></form></div>';
			if ( document.getElementById( 'content' ) ) {
				messageFind = $( formFind ).appendTo( '#content' );
			} else {
				messageFind = $( formFind ).appendTo( '#mw_content' );
			}
			messageFind.dialog( {
				title: '<img id="nameGuzzler-logo" src="//upload.wikimedia.org/wikipedia/commons/c/c1/Symbol_note_vote.svg" style="color:black;width:20px">&nbsp;' + translate( 'title' ),
				autoOpen: false,
				modal: true,
				width: 860,
				show: 'blind',
				hide: 'blind',
				buttons: [ {
					text: translate( 'send' ),
					click: function () {
						mw.notify( 'Sending ...', { title: 'nameGuzzler.js :', tag: 'nameGuzzler', autoHide : false } );
						$('.nameform').prop("disabled", true);
						lock = true;
						prepareChoice();
					}
				},{
					text: translate( 'close' ),
					click: function () {
						$( this ).dialog( 'close' );
					}
				} ]
			} );
			var portletLink = mw.util.addPortletLink( 'p-tb', '#', translate( 'title' ), 't-nameGuzzler', translate( 'nameGuzzler' ) );
			$( portletLink ).click( function () {
				$( 'div#nameGuzzler' ).dialog( 'open' );
				genFullChoice();
				return false;
			} );
			$( '#reset' ).click( function () {
				if(!lock){
					$('.checkbox').prop("checked", false);
					uncheckFullChoice();
				}
			} );
			$( '#select' ).click( function () {
				if(!lock){
					$('.checkbox').prop('checked',true);
					uncheckFullChoice();
				}
			} );
			$( '#auto' ).click( function () {
				if(!lock){
					$('.checkbox').prop('checked',false);
					for(var i = 0; i < nameGuzzler.length; i++){
						$('#' + nameGuzzler[i]).prop("checked", true);
					}
					uncheckFullChoice();
				}
			} );
			$( '.counting' ).click( function () {
				if(!lock){
					var count = $( '.checkbox' ).filter(':checked').length;
					$('#counter').text(count);
				}
			} );
			$( '#mode-label,#mode-aliases' ).click( function () {
				if(!lock){
					$('.checkbox').prop("checked", false);
					uncheckFullChoice();
				}
			} );
		} );
	}
	
	/*
	** genChoice
	*/
	function genFullChoice(){
		if(!$('#mode-aliases').prop("checked")){
			genFullLabels();
		}else{
			genFullAliases();
		}
	}

	/*
	** Generate full labels list
	*/

	function genFullLabels(){
		$('.checkbox').prop("disabled", true);
		api.get( {
			'action': 'wbgetentities',
			'ids': itemId,
			'props': 'labels'
		} )
		.done( function ( data ) {
			for ( id in data.entities[itemId].labels ) {
				fullLabels.push(id);
			}
			$('.checkbox').prop("disabled", false);
			uncheckFullChoice();
		} )
		.fail( function () {
			mw.notify( 'API Error', { title: 'nameGuzzler.js :', tag: 'nameGuzzler' } );
		} );
	}

	/*
	** Generate full labels list
	*/

	function genFullAliases(){
		$('.checkbox').prop("disabled", false);
		uncheckFullChoice();
	}
	
	/*
	** UncheckfullChoice
	*/
	
	function uncheckFullChoice(){
		if(!$('#mode-aliases').prop("checked")){
			uncheckFullLabels();
		}else{
			uncheckFullAliases();
		}
	}

	/*
	** Uncheck and disable all full label list
	*/

	function uncheckFullLabels(){
		for(var i = 0; i < fullLabels.length; i++){
			$('#' + fullLabels[i]).prop("disabled", true);
			$('#' + fullLabels[i]).prop("checked", false);
			$('#' + fullLabels[i] + "-label").css("color", "red");
		}		
	}

	/*
	** Uncheck and disable all full aliases list
	*/

	function uncheckFullAliases(){
		$('.checkbox').prop("disabled", false);
	}
	
	/*
	** PrepareChoice
	*/
	
	function prepareChoice(){
		if(!$('#mode-aliases').prop("checked")){
			prepareLabels();
		}else{
			prepareAliases();
		}
	}

	/*
	** Prepare the data to be send
	*/

	function prepareLabels(){
		var label = document.getElementById( 'label' ).value;
		var count = 0;
		var list = [];
		var jsonLabel = [];
		for(var n= 0; n < langlist.length ; n++){
			if(document.getElementById( langlist[n] ).checked){
				count++;
				list.push( langlist[n] );
				jsonLabel.push( {
					language: langlist[n],
					value: label
				} );
			}
		}
		setItem(JSON.stringify( { 'labels': jsonLabel } ), "Update " + count + " language(s) with the labels \"" + label + "\"" )
	}
	
	function prepareAliases(){
		var label = document.getElementById( 'label' ).value;
		var count = 0;
		var list = [];
		var jsonLabel = [];
		for(var n= 0; n < langlist.length ; n++){
			if(document.getElementById( langlist[n] ).checked){
				count++;
				list.push( langlist[n] );
				jsonLabel.push( [ {
					language: langlist[n],
					value: label,
					add: ""
				} ] );
			}
		}
		setItem(JSON.stringify( { 'aliases': jsonLabel } ), "Update " + count + " language(s) with the aliases \"" + label + "\"" )
	}

	/*
	** Send the input value on the edit menu
	*/
	function setItem( item, summary ) {
		api.postWithToken( 'csrf', {
			'action': 'wbeditentity',
			'id': itemId,
			'token': mw.user.tokens.get( 'csrfToken' ),
			'data': item,
			'summary': '[[User:Jitrixis/nameGuzzler.js|nameGuzzler]] ' + summary,
			'exclude': 'pageid|ns|title|lastrevid|touched|sitelinks|aliases|descriptions'
		} )
		.done( function ( data ) {
			if ( data.success === 1 ) {
				mw.notify( 'Sent : ' + summary, { title: 'nameGuzzler.js :', tag: 'nameGuzzler' } );
			} else {

				mw.notify( 'Error : ' + JSON.stringify( data ), { title: 'nameGuzzler.js :', tag: 'nameGuzzler' } );
			}
			$('.nameform').prop("disabled", false);
			lock = false;
			$( '#nameGuzzler' ).dialog( 'close' );
		} )
		.fail( function ( data ) {
			mw.notify( 'Error : ' + JSON.stringify( data ), { title: 'nameGuzzler.js :', tag: 'nameGuzzler' } );
			$('.nameform').prop("disabled", false);
			lock = false;
			$( '#nameGuzzler' ).dialog( 'close' );
		} );
	}

	$( document ).ready( labelLister );
} ( mediaWiki, jQuery ) );
});