Utente:Ricordisamoa/MediaWiki:Gadget-common.js

Da Wikisource.

Nota: dopo aver pubblicato, potrebbe essere necessario pulire la cache del proprio browser per vedere i cambiamenti.

  • Firefox / Safari: tieni premuto il tasto delle maiuscole Shift e fai clic su Ricarica, oppure premi Ctrl-F5 o Ctrl-R (⌘-R su Mac)
  • Google Chrome: premi Ctrl-Shift-R (⌘-Shift-R su un Mac)
  • Internet Explorer / Edge: tieni premuto il tasto Ctrl e fai clic su Aggiorna, oppure premi Ctrl-F5
  • Opera: premi Ctrl-F5.
/* global mw, $ */
// funzione simil, tuttofare ma indispensabile a autoreCitato
function simil(s1, s2, nc) {
	if (nc === undefined) nc = 4;
	var cont1 = 0;
	for (var i = 0; i <= (s1.length - nc); i += 1) {
		if (s2.indexOf(s1.substring(i, i + nc)) != -1) cont1 += 1;
	}
	return cont1 / i;
}

// modifico per aggiungere consensualmente eventuale tl|PNMIS

function newRi() {
	if (mw.config.get('wgCanonicalNamespace')=="Page" && !(/\{\{RigaIntestazione\||\{\{Ri\|/i).test(leggiBox("0"))) {
		var ri = find_stringa(testo2PagPrec[0], "{"+"{RigaIntestazione", "}}", 1, "{"+"{");
 
		if (ri==="") {
			testo2PagPrec[0]=testo2PagPrec[0].replace("{"+"{rh","{"+"{Rh");
			ri=find_stringa(testo2PagPrec[0], "{"+"{Rh", "}}", 1, "{"+"{");
			if (ri==="") ri="{"+"{RigaIntestazione|||}}";
		}
	var r = /\d+/;
	var np = ri.match(r);
	if (mw.config.get('wgTitle').indexOf("Drammaturgia di Lione Allacci.djvu") === 0) {
			np1=np*1+4;
			np2=np*1+5;
			ri="{"+"{RigaIntestazione|"+np1+"||"+np2+"}}";
		}
		else {
			ri = ri.replace(np, np * 1 + 2);
		}
	var pnmis=find_stringa(testoPagPrec[0],"{"+"{PNMIS","}}",1);
	if (pnmis !== "") { 
			ri+="\n"+pnmis;
		}
	var tlt=find_stringa(testoPagPrec[1],"{"+"{T|","}}",1);
	if (tlt !== "") {
			tlt=parseTemplate("T",tlt);
		}
	scriviBox(ri, "0");
	}
}

//modifica un dato link settando il parametro par in fondo all'URL
function setURLVar(link, par, val) {
	if (link) {
		href = link.attr("href");

		//rimuovi il parametro se c'era gia'
		if (href.indexOf(par) != -1) {
			regex = new RegExp(par + "=([a-z0-9]*)");
			href = href.replace(regex, "");
		}

		if (href.indexOf("?") == -1) {
			href += "?" + par + "=" + val;
		} else {
			href += "&" + par + "=" + val;
		}
		link.attr("href", href);
	}
}

function leggiBox(area) {
	if (area === undefined) {
		if (mw.config.get('wgCanonicalNamespace') == "Page") area = 1;
		else area = 0;
	}
	return $('textarea')[area].value;
}

function scriviBox(testo, area, ss, se) {
	if (area === undefined || area === "") {
		if (mw.config.get('wgCanonicalNamespace') == "Page") {
			area = 1;
		} else {
			area = 0;
		}
	}
	$('textarea')[area].value = testo;
	console.log("area:", area);
	if (ss !== undefined && se !== undefined) {
		$('textarea')[area].selectionStart = ss;
		$('textarea')[area].selectionEnd = se;
	}
}

/* conta il numero di occorrenze di stringa dentro testo*/
function count(testo, stringa) {
	n = 0;
	while (testo.indexOf(stringa) > -1) {
		n = n + 1;
		testo = testo.replace(stringa, "");
	}
	return n;
}

/* 
Ricerca nella stringa testo la sottostringa che inizia con idi e termina con idf.  (idi e idf sono stringhe).
 
Se dc ("delimitatori compresi") è 1, restituisce la sottostringa completa di idi e idf; se dc è 0, restituisce la stringa
senza delimitatori; parametro opzionale con default 0.
Per risolvere correttamente il caso di ricerca di tag annidati, come i template, in cui l'identificatore iniziale ha una 
parte non aspecifica, e una parte specifica, può essere passato un quinto parametro, che definisce  la parte aspecifica dell'identificatore iniziale.
 
Esempio: volendo ottenere l'intero contenuto del template {{centrato|{{sc|Testo di prova}}|l=18em}}, il risultato corretto
NON proviene dalla ricerca find_stringa("{{centrato|","}}",1), perchè sarebbe {{centrato|{{sc|Testo di prova}}. 
Impostando invece find_stringa("{{centrato|","}}",1,"{{"), visto che "{{" è la parte aspecifica del primo delimitatore,
si ottiene il risultato corretto, a prescindere dal numero dei template annidati. 
 
Se la sottostringa non viene trovata, la funzione restituisce una stringa vuota "". 
 
*/
function find_stringa(testo, idi, idf, dc, x) {
	idip = testo.indexOf(idi);
	idfp = testo.indexOf(idf, idip + idi.length) + idf.length;
	if (idip > -1 && idfp > -1) {
		if (x !== "") {
			while (count(testo.slice(idip, idfp), x) > count(testo.slice(idip, idfp), idf)) {
				idfp = testo.indexOf(idf, idfp) + idf.length;
			}
		}
		if (dc === 0) {
			vvalore = testo.slice(idip + idi.length, idfp - idf.length);
		} else {
			vvalore = testo.slice(idip, idfp);
		}
	} else {
		vvalore = "";
	}
	return vvalore;
}

function cod(testo) {
	var l = produciLista(testo, "{"+"{", "}}", 1, "{"+"{");
	for (var i = 0; i < l.length; i += 1) {
		testo = testo.replace(l[i], l[i].replace(/\|/g, "__!__"));
	}
	l = produciLista(testo, "[[", "]]", 1, "[[");
	for (var i = 0; i < l.length; i += 1) {
		testo = testo.replace(l[i], l[i].replace(/\|/g, "__!__"));
	}
	return testo;
}

// delim true: con delimitatori, false: senza delimitatori
function produciLista(testo, s1, s2, delim, x) {
	lista = [];
	while (find_stringa(testo, s1, s2, true, x) > "") {
		elemento = find_stringa(testo, s1, s2, true, x);
		testo = testo.replace(elemento, "");
		if (delim) {
			lista.push(elemento);
		} else {
			lista.push(elemento.slice(s1.length, - s2.length));
		}
	}
	return lista;
}

function parseTemplate(template, testo) {
	if (testo === undefined) testo = leggiBox();
		var cap=template.substring(0,1).toLocaleUpperCase()+template.substring(1);
		testo=testo.replace("{"+"{"+cap,"{"+"{"+template);
	var t = find_stringa(testo, "{"+"{" + template, "}}", 1, "{"+"{");
	var l = []; // lista delle keys
	t = "0=" + t.substring(2, t.length - 2); // nome del template in parametro "0"
	l.push["0"];
	var ts = {};
	var n = 1;
	t = cod(t);
	t = t.split("|");

	// element for element
	for (i = 0; i < t.length; i += 1) {
		// case param is positional
		if (t[i].indexOf("=") == -1) {
			t[i] = n + "=" + t[i];
			n = n + 1;
		}
		var els = [];
		els[0] = t[i].substring(0, t[i].indexOf("=")).trim();
		els[1] = t[i].substring(t[i].indexOf("=") + 1).trim();
		if (els[1][els[1].length - 1] == "\n") els[1] = els[1].substring(0, els[1].length - 1);

		ts[els[0]] = decod(els[1]);
		l.push(els[0]);
	}

	return [ts, l];
}


function decod(testo) {
	testo = testo.replace(/__!__/g, "|");
	return testo;
}

function templateObj(nomeTemplate) {
	data = parseTemplate(nomeTemplate);
	this.keys = data[1];
	this.dict = data[0];
}

function rewriteTemplate(x) {
	var testo = "";
	$.each(x[1], function (indice, valore) {
		if (valore != "0") testo += " | " + valore + " = " + x[0][valore] + "\n";
	});
	testo = "{"+"{" + x[0]["0"] + "\n" + testo + "}}\n";
	testo = testo.replace(/\n\s\|\s\d*\s=\s/g, "\n | ");
	return testo;
}


/********************* documentazione ***********************
Lo script legge via AJAX il contenuto della pagina di cui gli viene passato il titolo e restituisce una liste di tre elementi stringa:
1. eventuale wikicode header (solo nsPagina);
2. wikicode corpo (in tutti i casi);
3. eventuale wikicode footer (solo nsPagina)
 
Nota: 
1. i caratteri & " < > sono contenuti come html entities
2. gli spazi sono conservati come tali 
3. temporaneamente viene aggiunto ai codici template e ai tag html un colore testo
*/
function acchiappaWikicode(pagina, progetto) {
	if (pagina === undefined) pagina = mw.config.get('wgPageName');
	if (progetto === undefined) {
		progetto = "";
	} else {
		progetto = "//" + progetto;
	}
	var contenuto = $.ajax({
		url: progetto + "/w/index.php?action=raw&title=" + pagina,
		async: false
	}).responseText.replace(/</g, "&lt;").replace(/>/g, "&gt;");
 
	var l = produciLista(contenuto, "{"+"{", "}}", 1, "{"+"{");
	for (var i = 0; i < l.length; i += 1) {
		contenuto = contenuto.replace(l[i], '<span style="color: red;">' + l[i] + '</span>');
	}
	contenuto = contenuto.replace(/\&lt;/g, '<span style="color:blue">&lt;').replace(/\&gt;/g, '&gt;</span>').replace(/\n/g, "<br />");
	if (mw.config.get('wgCanonicalNamespace') == "Page") {
		var noincludeList = produciLista(contenuto, '<span style="color:blue">&lt;noinclude&gt;</span>', '<span style="color:blue">&lt;/noinclude&gt;</span>', 1);
		var header = noincludeList[0];
		var footer = noincludeList[noincludeList.length - 1];
		var body = find_stringa(contenuto, header, footer, 0);
		contenuto = [header, body, footer];
	} else {
		contenuto = ["", contenuto, ""];
	}
	return contenuto;
}

function impostaBottoni(fun) {
	$(document).ready(function () {
		$('#wpSave').click(fun);
		$('#wpPreview').click(fun);
		$('#wpDiff').click(fun);
	});
}

/* funzione di creazione della bottoniera 
Dopo l'esecuzione, esiste #newtattoo        */

function creaBottoniera() {
	$('#' + (mw.user.options.get('skin') === 'modern' ? 'mw_' : '') + 'content')
	.append('<div id="newtattoo" align="right" style="position:fixed;bottom:0; right:0; background-color:white; border: 1px solid; border-color:#F0F0F0; z-index:1500;"></div>');
}

/* newButton accetta parametri usuali oppure un oggetto; l'oggetto deve avere questa struttura:
newButton({nome:"...", funzione:"...", azione:"...", messaggio:"...", classe:"...", stile:"...", namespaces:"..."});

Sono obbligatori solo nome, funzione, azione
Namespaces deve contenere una sequenza di namespaces (Page per Pagina), separati da | , al di fuori dei quali il bottone non sarà visualizzato; ns0 può essere indicato con Main, Principale o con uno spazio.

spostata in Mediawiki:Gadget-common.js */


function newButton(nome, funzione, azione, messaggio) { 
// azione è una stringa composta da v,e,s,h rispettivamente view,edit,submit,history
// se nome è un oggetto svolgilo
	var p;
	if (typeof(nome) === "string") {
		p = {
			nome: nome,
			funzione: funzione,
			azione: azione,
			messaggio: messaggio
		};
	} else {
		p = nome;
	}
	if (p.messaggio===undefined) p.messaggio="Nessun aiuto registrato";
	if (p.classe===undefined) p.classe="baseButton";
	if (p.stile===undefined) p.stile="display:inline";
	if (p.namespaces!==undefined) {
		var listaNamespaces=p.namespaces.split("|");
		for (var i=0; i<listaNamespaces.length; i+=1) {
			listaNamespaces[i]=$.trim(listaNamespaces[i]); 
			if (["ns0", "Main", "Principale"].indexOf(listaNamespaces[i]) !== -1) {
				listaNamespaces[i] == "";
			}
		}
		if ($.inArray(mw.config.get('wgCanonicalNamespace'),p.namespaces.split(","))==-1) return;
	}
// Passo 1: se newtatooo non esiste, lo crea
	if ($("#newtattoo").length==0) creaBottoniera();
	// fine se azione=history
	if (mw.config.get('wgAction') === "history") {
		return;
	}
	// normalizzazione function
	if (p.funzione.indexOf("(") === -1 && p.funzione.indexOf(")") === -1) {
		p.funzione += "()";
	}
	// default: bottone presente in view, edit, 
	if (p.azione === undefined) {
		p.azione = "ves";
	}
		// messaggio di default
	if (p.messaggio === undefined) {
		p.messaggio = "Nessun messaggio di aiuto registrato";
	}
	// valutazione condizione di visualizzazione
	if (mw.config.get('wgAction') === "edit" && p.azione.indexOf("e") === -1) {
		return;
	}
	if (mw.config.get('wgAction') === "view" && p.azione.indexOf("v") === -1) {
		return;
	}
	if (mw.config.get('wgAction') === "submit" && p.azione.indexOf("s") === -1) {
		return;
	}
	// caso pulsante=immagine
	if (p.nome.substring(0, 2) == "//") {
		var html = '<img class="'+p.classe+'" style="'+p.stile+'" src="' + p.nome + '" onclick="' + p.funzione + '" title="' + p.messaggio +'"';
				if (p.ondblclick!==undefined) html+=' ondblclick="'+p.ondblclick+'"';
				html+='/>';
	}
	// caso pulsante=label
	else {
		var html = '<button class="'+p.classe+'" style="'+p.stile+'" type="button" title="' + p.messaggio + '" onclick="' + p.funzione +'"';
				if (p.ondblclick!==undefined) html+=' ondblclick="'+p.ondblclick+'"';
				html+='><small>' + p.nome + '</small></button>';                
	}
		$("#newtattoo").append($(html));
	return false;
}

function splitRiga() {
   var t=selection(); 
   var ps=t[2].indexOf("\n"); 
   var ts=t[2].substring(0,ps);
   t[2]=t[2].substring(ps)+"\n"+ts;
   scriviBox(t.join(""));
}

/**
 * http://www.openjs.com/scripts/events/keyboard_shortcuts/
 * Version : 2.01.B
 * By Binny V A
 * License : BSD
 */
var shortcut = {
	'all_shortcuts':{},//All the shortcuts are stored in this array
	'add': function(shortcut_combination,callback,opt) {
		//Provide a set of default options
		var default_options = {
			'type':'keydown',
			'propagate':false,
			'disable_in_input':false,
			'target':document,
			'keycode':false
		};
		if(!opt) opt = default_options;
		else {
			for(var dfo in default_options) {
				if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
			}
		}
 
		var ele = opt.target;
		if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
		var ths = this;
		shortcut_combination = shortcut_combination.toLowerCase();
 
		//The function to be called at keypress
		var func = function(e) {
			e = e || window.event;
 
			if(opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields
				var element;
				if(e.target) element=e.target;
				else if(e.srcElement) element=e.srcElement;
				if(element.nodeType==3) element=element.parentNode;
 
				if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
			}
 
			//Find Which key is pressed
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
			var character = String.fromCharCode(code).toLowerCase();
 
			if(code == 188) character=","; //If the user presses , when the type is onkeydown
			if(code == 190) character="."; //If the user presses , when the type is onkeydown
 
			var keys = shortcut_combination.split("+");
			//Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
			var kp = 0;
 
			//Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
			var shift_nums = {
				"`":"~",
				"1":"!",
				"2":"@",
				"3":"#",
				"4":"$",
				"5":"%",
				"6":"^",
				"7":"&",
				"8":"*",
				"9":"(",
				"0":")",
				"-":"_",
				"=":"+",
				";":":",
				"'":"\"",
				",":"<",
				".":">",
				"/":"?",
				"\\":"|"
			}
			//Special Keys - and their codes
			var special_keys = {
				'esc':27,
				'escape':27,
				'tab':9,
				'space':32,
				'return':13,
				'enter':13,
				'backspace':8,
 
				'scrolllock':145,
				'scroll_lock':145,
				'scroll':145,
				'capslock':20,
				'caps_lock':20,
				'caps':20,
				'numlock':144,
				'num_lock':144,
				'num':144,
 
				'pause':19,
				'break':19,
 
				'insert':45,
				'home':36,
				'delete':46,
				'end':35,
 
				'pageup':33,
				'page_up':33,
				'pu':33,
 
				'pagedown':34,
				'page_down':34,
				'pd':34,
 
				'left':37,
				'up':38,
				'right':39,
				'down':40,
 
				'f1':112,
				'f2':113,
				'f3':114,
				'f4':115,
				'f5':116,
				'f6':117,
				'f7':118,
				'f8':119,
				'f9':120,
				'f10':121,
				'f11':122,
				'f12':123
			};
 
			var modifiers = { 
				shift: { wanted:false, pressed:false},
				ctrl : { wanted:false, pressed:false},
				alt  : { wanted:false, pressed:false},
				meta : { wanted:false, pressed:false}	//Meta is Mac specific
			};
 
			if(e.ctrlKey)	modifiers.ctrl.pressed = true;
			if(e.shiftKey)	modifiers.shift.pressed = true;
			if(e.altKey)	modifiers.alt.pressed = true;
			if(e.metaKey)   modifiers.meta.pressed = true;
 
			for(var i=0; k=keys[i],i<keys.length; i++) {
				//Modifiers
				if(k == 'ctrl' || k == 'control') {
					kp++;
					modifiers.ctrl.wanted = true;
 
				} else if(k == 'shift') {
					kp++;
					modifiers.shift.wanted = true;
 
				} else if(k == 'alt') {
					kp++;
					modifiers.alt.wanted = true;
				} else if(k == 'meta') {
					kp++;
					modifiers.meta.wanted = true;
				} else if(k.length > 1) { //If it is a special key
					if(special_keys[k] == code) kp++;
 
				} else if(opt['keycode']) {
					if(opt['keycode'] == code) kp++;
 
				} else { //The special keys did not match
					if(character == k) kp++;
					else {
						if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
							character = shift_nums[character]; 
							if(character == k) kp++;
						}
					}
				}
			}
 
			if(kp == keys.length && 
						modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
						modifiers.shift.pressed == modifiers.shift.wanted &&
						modifiers.alt.pressed == modifiers.alt.wanted &&
						modifiers.meta.pressed == modifiers.meta.wanted) {
				callback(e);
 
				if(!opt['propagate']) { //Stop the event
					//e.cancelBubble is supported by IE - this will kill the bubbling process.
					e.cancelBubble = true;
					e.returnValue = false;
 
					//e.stopPropagation works in Firefox.
					if (e.stopPropagation) {
						e.stopPropagation();
						e.preventDefault();
					}
					return false;
				}
			}
		}
		this.all_shortcuts[shortcut_combination] = {
			'callback':func, 
			'target':ele, 
			'event': opt['type']
		};
		//Attach the function with the event
		if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
		else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
		else ele['on'+opt['type']] = func;
	},
 
	//Remove the shortcut - just specify the shortcut and I will remove the binding
	'remove':function(shortcut_combination) {
		shortcut_combination = shortcut_combination.toLowerCase();
		var binding = this.all_shortcuts[shortcut_combination];
		delete(this.all_shortcuts[shortcut_combination])
		if(!binding) return;
		var type = binding['event'];
		var ele = binding['target'];
		var callback = binding['callback'];
 
		if(ele.detachEvent) ele.detachEvent('on'+type, callback);
		else if(ele.removeEventListener) ele.removeEventListener(type, callback, false);
		else ele['on'+type] = false;
	}
}
// funzione per gestire l'icona Link a immagini IA in nsIndice
$(document).ready(function () {
	if (mw.config.get('wgCanonicalNamespace')=="Index") {
		var dataIA=$("span.data").data("fonte");
		
		
		if (dataIA.indexOf("[")==-1) {
			iaItem=find_stringa(dataIA+"/","/details/","/",0); //prendi cio' che si trova tra /details/ e il successivo /
		}
		else {
			iaItem=find_stringa(dataIA,"/details/"," ",0);     //prendi cio' che si trova tra /details/ e il successivo spazio
		}
		if (iaItem!="") {     // fonte contiene un link come stringa
			iaImageLink="//archive.org/download/"+iaItem+"/"+iaItem+"_jp2.zip/";
			$("div[title='IA HR images link'] a").attr("href",iaImageLink).removeClass("image").attr("target","_blank");
		
		}
		else {
			$("div[title='IA HR images link']").remove();
		}
	}
});