Utente:Alex brollo/autoPt.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.
// ==UserScript==
// @name    Ruthven based on it:MediaWiki:Tools.js and it:MediaWiki:Common.js
// @version  1.1
// @grant    none
// ==/UserScript==

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

			// di default il box principale di edit
			mw.activeElement=$("#wpTextbox1")[0];
			$("textarea, input[type!='checkbox'][type!='button'][type!='search'][type!='hidden'][type!='submit'][name!='wpAntispam']").focusin(function () {
				mw.activeElement = this;
			});

			$testoPagCorr = ["","",""];

			$testoPagPrec = ["", "", ""];

			// CREA PULSANTE
			var ptButton = new OO.ui.ButtonWidget( { 
				label: 'Pt',
				id: 'pt-button-widget',
				framed: false,
				title: 'Appreca \'o template Pt'
			} );
			ptButton.on( 'click', function ( context ){ 
				autoPt(); 
			} );

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


function splitPagina (tpp) {
	var testo = ["", "", ""];
	testo[0] = tpp.substring(0, tpp.indexOf("</noinclude>") + 12);
	testo[2] = tpp.substring(tpp.lastIndexOf("<noinclude>"));
	testo[1] = tpp.substring(testo[0].length, tpp.length - testo[2].length);
	return testo;
}


// riscrive mw.activeElement e ristabilisce il focus/la selezione attiva
// riceve un array tipo [testo precedente, testo selezionato, testo seguente]
function scriviSel (t) {
	mw.activeElement.value=t.join("");
	mw.activeElement.selectionStart=t[0].length;
	mw.activeElement.selectionEnd= t[0].length + t[1].length;
	mw.activeElement.focus();
}

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;
}

/* Nuova versione selection che usa mw.activeElement */
function selection (area) {

	var txt=mw.activeElement.value;
	var s=[];
	s[0]=txt.substring(0,mw.activeElement.selectionStart);
	s[1]=txt.substring(mw.activeElement.selectionStart,mw.activeElement.selectionEnd);
	s[2]=txt.substring(mw.activeElement.selectionEnd);
	return s;
}

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

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 === false ) {
			vvalore = testo.slice( idip + idi.length, idfp - idf.length );
		} else {
			vvalore = testo.slice( idip, idfp );
		}
	} else {
		vvalore = "";
	}
	return vvalore;
}


function scriviBox (testo, area, ss, se) {

	if (area === undefined || area === "") {
		if (mw.config.get('wgCanonicalNamespace') == "Page" || $("#editBox").length == 1) {
			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;
	}
}


function autoPt() {

	var t = [],
			rFin = /\ (\w+’*\w+)-$/,			// parola finale ifenata
			rPtIniz = /^\{\{pt\|/i,		// pt in testa sulla pagina corrente
			rPtFin = /\{\{pt\|(.+)-\|\}\}/i,	// pt di tipo finale
			rHyp2 = /^[^ \n\t]+/,
			hyp = "",
			hyp2 = "",
			l = [],
			prePt = "",
			headTxt="",
			rht=/^(({{nop}})*\n*)/;
	t = selection();

	if (t[1].length > 0) { // se c'è una selezione di testo...
		
		if (t[0].length === 0) { //allora va applicato un pt-before... 

			var pn = mw.config.get( 'wgPageName' ).split( "/" );

			if ( parseInt(pn[1]) > 1) {

				var npp = pn[0] + "/" + ( parseInt( pn[1] ) - 1 );
				var params = {
					action: 'parse',
					page: npp,
					prop: 'wikitext',
					format: 'json'
				},
						api = new mw.Api();
				api.get( params ).done( function ( data ) {

					var tpp = data.parse.wikitext['*'];
					console.log('parsed ' + params.page ); 
					$testoPagPrec = splitPagina( tpp );
					if ( rPtFin.exec( $testoPagPrec[ 1 ] ) !== null && rPtIniz.exec( t ) === null ) {
						hyp = rPtFin.exec( $testoPagPrec[ 1 ] )[ 1 ];
						hyp2 = rHyp2.exec( t[1] );
						t [1] = t[1].replace( hyp2, "" );
						t[1] = "{{Pt|" + hyp2 + "|" + hyp + hyp2 + "}}";
					}

					var tt = headTxt + t[0] + t[1] + t[2];
					scriviBox( tt ); 
				}).fail ( function () {
					console.log('API : nun aggio pigliato nisciuno testo!');
				}); 
			}
		} else if ( t[2].length === 0 ) { // siamo a fine pagina

			 // TODO: Da controllare se finisce con un -
			t[1] = "{{Pt|" + t[1] + "|}}";

		}
		scriviSel( t );

	} else {   // invece se non c'è alcuna selezione di testo...
		var tx = '';
		tx = leggiBox();
		headTxt = rht.exec( tx )[ 0 ];
		if ( tx.indexOf( "{{nop}}" ) === 0 ) 
			tx = tx.replace( "{{nop}}", "" );
		tx = $.trim( tx );

		// se la pagina precedente ha un pt di tipo finale
		// e la pagina corrente non ha un pt di tipo iniziale
		// allora applica un pt iniziale

		// se la pagina corrente termina con parola ifenata
		// allora applica pt finale sulla
		if ( rFin.exec( tx ) !== null ) {
			hyp = rFin.exec( tx )[ 1 ]; //parola ifenata senza trattino
			tx = tx.substr( 0, tx.search( rFin ) + 1 ) +
				"{{Pt|" + hyp + "-|}}";
		}

		var pn = mw.config.get( 'wgPageName' ).split( "/" );

		if ( parseInt(pn[1]) > 1) {

			var npp = pn[0] + "/" + ( parseInt( pn[1] ) - 1 );
			var params = {
				action: 'parse',
				page: npp,
				prop: 'wikitext',
				format: 'json'
			},
					api = new mw.Api();

			// var wikitext = "";
			api.get( params ).done( function ( data ) {

				var tpp = data.parse.wikitext['*'];
				console.log('parsed ' + params.page ); 
				$testoPagPrec = splitPagina( tpp );
				if ( rPtFin.exec( $testoPagPrec[ 1 ] ) !== null && rPtIniz.exec( tx ) === null ) {
					hyp = rPtFin.exec( $testoPagPrec[1] )[ 1 ];
					hyp2 = rHyp2.exec( tx );
					tx = "{{Pt|" + hyp2 + "|" + hyp + hyp2 + "}}" + tx.replace(hyp2, "");
					console.log('T: ' + tx);
				}
				scriviBox( headTxt + tx ); 

			}).fail ( function () {
				console.log('API : nun aggio pigliato nisciuno testo!');
			}); 
		} else {
			scriviBox( headTxt + tx ); 
		}
	}
}