Utente:Alex brollo/Rh.js

'A Wikisource.

Notarella: Aroppo pubbreca putisse necessità 'e pulezzà 'a caché d' 'o navigatóre pe vedé 'e cagnamienti.

  • Firefox / Safari: Sprémme 'o buttóne maiuscole e ffà clic ncopp'a Recarreca, o pure spremme Ctrl-F5 o Ctrl-R (⌘-R ncopp'a Mac)
  • Google Chrome: spremme Ctrl-Shift-R (⌘-Shift-R ncopp'a nu Mac)
  • Internet Explorer/edge: Spremme 'o buttóne Ctrl pe' tramente ca faie click ncopp'a Refresh, o pure spremmere Ctrl-F5
  • Opera: Vaje addò 'o Menu → Mpustaziune (Opera → Mpustaziune ncopp' 'o Mac) e po' ncopp'a Privacy & sicurezza → Pulezza date d' 'o browser → Immaggene e file d' 'a cache.
/* Schema logico
Aggiungere pulsante in toolbox, gruppo "Avanzate"
preparare una funzione di lettura del wikicode di due pagine prima
parsing dell'eventuale Rh e individuazione del numero arabo pagina
sua sostituzione con numero + 2 (lasciando intatto tutto il resto)
aggiornamento header 
*/

mw.loader.using( [ 'mediawiki.util',
					'oojs-ui-core',
					'ext.wikiEditor'
								 ], function () {
	// Only for NS Paggena
	if ( mw.config.get('wgCanonicalNamespace') === 'Page' && 
	(mw.config.get("wgAction")==="edit" ||mw.config.get("wgAction")==="submit")  ) {
		$(document).ready(function() {

			// bozza funzioni specifiche
			if ( typeof $ != 'undefined' && typeof $.fn.wikiEditor != 'undefined' ) { 
				$( function() {

					// CREA PULSANTE
					var rhButton = new OO.ui.ButtonWidget( { 
						label: 'Rh',
						id: 'rh-button-widget',
						framed: false,
						title: 'Miette \'a capata a\' paggena'
					} );
					rhButton.on( 'click', function ( context ) { 
						autoRh(); 
					} );

					$( '#wikiEditor-section-advanced' ).append( rhButton.$element );

					// $('[accesskey=y]').removeAttr('accesskey');
					// $('.wikiEditor-ui-toolbar [title="Indenta i versi selezionati [alt-shift-y]"]').attr('accesskey', 'y');
				});}
		});
	}
});


// Returns the current page number
// Assumes there is only one numeric value in Rh
// @param rh - the Rh template encoded
function getPageNumber ( rh ) {
	
	var i;
	
	for ( i in rh[0] ) {
		if ( rh[0][i] === undefined ) 
			continue;
		
		rh[0][i] = rh[0][i].trim();
		
    if ( rh[0][i] == '' )
			continue;
		
		// var oldRh = rh[0][i]; 
		var num = rh[0][i].replace(/\D/g, '');
		
		if ( !num )
			continue;
		
		var n = Math.floor( Number( num ) ) + 2;
		
		rh[0][i] = rh[0][i].replace(/(\d+)/g, n);
		
		// console.log( ' num: ' + rh[0][i] );
		
		return n;
	}
	
	return 0;
}

// Chiamma 'o Rh novo
function autoRh() {
	
	function incrementa (t) {
		var pagina =/(\d+)/.exec(t)[1];
		var pnew = ( pagina * 1 + 2 ) + ""; 
		return t.replace( pagina, pnew );
	}	
	
	/* funzione temporanea test */
	// $("#wpHeaderTextbox").val("{{Rh|||}}");
	// rht=/^(({{[Rr]h\|.*}})*\n*)/;
	
	var templateRh = 'Rh';	
	var val = [];
	var p;
	
	p =  nomePagPrec2 ();
	
	//var tx = '';
	//	tx = leggiBox();
	
	var pprec2 = '';
	pprec2 = pageGet( p );
	
	// normalizzazione Header
	pprec2 = pprec2.replace( "{{rh|", "{{Rh|" );
	
	var rh = '';
	rh = parseTemplate( templateRh, pprec2 );
			
	var npn = getPageNumber( rh );
	
	// Error in getting page number
	if ( npn === 0 ) return;
	
	var rhw = '';
	var rh_current='';
	rhw = rewriteTemplate ( rh );
	//console.log(npn,rhw);  // vediamo : fin qui OK
    // Sostituisce Rh col valore modificato
    // e conserva altro testo eventualmente presente
	var capata=$("#wpHeaderTextbox").val().replace("{{rh|","{{Rh");
	rh_current=find_stringa(capata, "{{Rh|","}}",1,"{{");
	// casi
	// se l'header non contiene un rh aggiungilo; nota: non copia eventuale codice dell'header presente nella pagina -2
	// e non sovrascrive un eventuale Rh presente
	if (rh_current===rhw) return;
	if (rh_current==="") {
		$("#wpHeaderTextbox").val(rhw+capata);
	} else {
		if (confirm("Sostituisco il Rh esistente?")) {
			$("#wpHeaderTextbox").val(capata.replace(rh_current,rhw));
			}
	}
	
}


// funzioni globali 

// dato un wgPageName restituisce il suo wikicode
function pageGet( pagina ) {
	if ( pagina === undefined ) pagina = mw.config.get( "wgPageName" );
	var contenuto = $.ajax({
		url: "/w/index.php?action=raw&title=" + pagina,
		async: false
	}).responseText;
	return contenuto;
}

// ricava da wgPageName il nome della pagina -2 (restituisce "" se il numero pagina < 3)
function nomePagPrec2 () {
	var header
	if (document.getElementsByClassName('oo-ui-iconElement-icon oo-ui-icon-notice').length)
		// Siamo nel caso Edit-in-sequence
		header = document.getElementById('firstHeadingTitle').textContent
	else
		header = mw.config.get( "wgPageName" )
	var pagina = header.split( "/" );
	pagina[1] = pagina[1] * 1;
	if ( pagina[1] > 2 ) 
		return pagina[0] + "/" + ( pagina[1] - 2 ); 
	else 
		return "";
}

/**
 * Esegue il parsing di un template (gestisce template annidati, parametri ordinali e nominali); 
 *
 * @param {string} template Nome del template
 * @param {string} testo Testo da analizzare
 * @return {dizionario} [ ts, l ] Dove ts è un dizionario dei parametri e l è la lista dei parametri
 */
function parseTemplate( template, testo ) {
	
	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, "__!__").replace(/=/g, "__eq__") );
		}
		l = produciLista(testo, "[[", "]]", 1, "[[");
		for (i = 0; i < l.length; i += 1) {
			testo = testo.replace(l[i], l[i].replace(/\|/g, "__!__"));
		}
		return testo;
	}
	
	function decod(testo) {
		testo = testo.replace(/__!__/g, "|").replace(/__eq__/g, "=");
		return 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, i;
	t = cod( t );
	t = t.split("|");

	// element for element
	for (i = 0, n = 0; i < t.length; i++, n++ ) {
		// case param is positional
		if (t[i].indexOf("=") == -1) {
			t[i] = n + "=" + t[i];
		}
		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 ];
}


/**
 * Riscrive il template dall'oggetto prodotto da parseTemplate, 
 * minificato (singola linea) o espanso (più linee).
 *
 * @param {dizionario} x Template codificato.
 * @param {bool} mini 
 * default minificato
 * @return {string} testo Template sotto forma di stringa
 */
function rewriteTemplate ( x, mini ) {	

	var testo = "";
	
	if ( mini === undefined ) mini = true;
	if ( mini ) { 
		$.each( x[1], function ( indice, valore ) {
			if ( (/^\d+$/).test( valore ) ) 
				testo += "|" + x[0][valore];
			else
				testo += "|" + valore + "=" + x[0][valore];
		});
		testo = "{{" + testo.substring( 1 ) + "}}";
	} else { 
		$.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;
}


/**
 * Funzione di ricerca sottostringhe
 * Gestisce le sottostringhe annidate (template in template, elementi html/xml); 
 * restituisce la prima occorrenza
 *
 * @param {string} testo Testo nel quale cercare
 * @param {string} idi indice
 * @param {string} idf indice
 * @param {string} dc indice
 * @param {string} x stringa da cercare
 * @return {number} vvalore Prima occorrenza della sottostringa
 */
// 
// 
function find_stringa  (testo, idi, idf, dc, x) {
	
	var idip, idfp, vvalore;
	
	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 === false ) {
			vvalore = testo.slice( idip + idi.length, idfp - idf.length );
		} else {
			vvalore = testo.slice( idip, idfp );
		}
	} else {
		vvalore = "";
	}
	return vvalore;
}


// utilizza find_stringa e restituisce, con gli stessi parametri, la lista delle occorrenze
// delim true: con delimitatori, false: senza delimitatori
function produciLista (testo, s1, s2, delim, x) {
	var 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;
}


// conta le occorrenze di una sottostringa in una stringa
function count(testo, stringa) {
	var n = 0;
	if ( testo !== "" && stringa !== "" ) {
		while ( testo.indexOf( stringa ) > -1 ) {
			n = n + 1;
			testo = testo.replace (stringa, "" );
		}
	}
	return n;
}


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