Vai al contenuto

MediaWiki:Gadget-eis.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)
  • Edge: tieni premuto il tasto Ctrl e fai clic su Aggiorna, oppure premi Ctrl-F5.
// Eis versione 29.11.2021, implementa openSeadragon, vedi commento OpenSeadragon (righe 366 e segg.)
if (typeof alex === 'undefined') {
    alex={};
}

eis={};
eis.cp={};
(function ($,mw) {
	// console.log("passo 1");
	if (mw.config.get("wgCanonicalNamespace")!=="Page" || mw.config.get("wgAction")!=="edit") { 
		// console.log("eis non eseguito"); 
		return false;
	} else {
		$(".prp-page-container").css("height","100%");$(".prp-layout-is-horizontal #wpTextbox1").attr("rows","6");
		eis.base=/Pagina:(.+)\/\d+$/.exec(mw.config.get("wgPageName"))[1];
		eis.html=$.ajax({
			url: "/w/index.php?action=render&title=Indice:" + normUrl(eis.base),
			async: false
		}).responseText;
		eis.indexLength=$(".pagineDellEdizione a", $(eis.html)).length;
	}
	// console.log("passo 2");
	activate();


	/* passo 1 :  costruire l'ambiente */
	
	
	// in nsPage, and in view mode, eis environment is built
	function normUrl(nomePagina) {
		return encodeURI(nomePagina.replace(/ /g,"_")).replace(/&/g,"%26");
	}
	
	
	function activate() {

		
		// access button
		
		if (!mw.user.options.get("gadget-barbaforcutanew")) {
			
			mw.util.addPortletLink('p-views', '#', 'eis', 'ca-eis', 'Attiva eis');
			$('#ca-eis').click(function() {
				$("#wptextbox1").css("font-size",".9pc");
				creaEis();
				pp();
			});
		// loading wikitext of three pages
	
		} else {
			$('<button id="ca-eis" type="button">eis</button>').click(function() {
				$("#wpTextbox1").css("font-size",".9pc");
				creaEis();
				pp();
			}).appendTo($(".editButtons"));
		// loading wikitext of three pages
		}
		
		return false;
	}
	
	shortcut.add('Ctrl+Alt+U', function() {navigator.clipboard.writeText('https:'+$('.prp-page-image img').attr('src')); 
	mw.alertMessage("Image URL", "L'indirizzo dell'immagine della pagina è stata caricata negli appunti");});
	/*img_enlarge=function(){
		var img=$(".prp-page-image img")[0];
		$(".prp-page-image img").css({"width":Math.trunc(img.width*1.12)+"px",
		"height":Math.trunc(img.height*1.12)+"px",
		"top":Math.trunc(img.top-img.height*0.03)+"px",
		});
		return false;
	};
	
	img_reduce=function(){
		var img=$(".prp-page-image img")[0];
		$(".prp-page-image img").css({"width":Math.trunc(img.width/1.12)+"px",
		"height":Math.trunc(img.height/1.12)+"px",
		"top":Math.trunc(img.left+img.width*0.03)+"px"
		});
		return false;
	};
	
	shortcut.add("Ctrl+Alt+i", function() {
		$(".openseadragon-container").remove();
		$(".prp-page-image img").css("display","initial");
		$(".prp-page-image").attr("id","prp-page-image");
		$(".prp-page-image").css("overflow","auto");
		$(".prp-page-image img").draggable();
		$("#prp-page-zoomIn").click(img_enlarge);
		$("#prp-page-zoomOut").click(img_reduce);
		mw.alertMessage("MemoRegex", "Openseadragon è stato disattivato");
		});
	*/
	// initializing function, it disables some buttons, builds preview box, build action buttons
	function creaEis() {
	    // disabilitazioni
		$("#ca-proofreadPagePrevLink a, #ca-proofreadPageNextLink a").remove();
		$("#wpSave, #wpPreview, #wpDiff, #wikiPreview").remove();
		$(".mw-summary, .editCheckboxes").remove();
		$("#ca-eis").remove();
		// disabilito la disabilitazione di OCT tesseract
		// $("a[title='Get the text by OCR']").remove();
		$('body').append(
			'<div id="findReplaceEis_box" style="display:none; font-size:90%; width:500px;position:fixed; z-index:1500;top:0px;right:0px;background-color:white;border:2px solid #0645AD;padding:10px">' +
			'<div style="float:left">Cerca testo:</div>' +
			'<div style="float:right"><input type="text" id="findReplaceEis_find" size="30" style="background-color:#efefef" readonly/></div>' +
			'<div style="clear:both;float:left">Sostituisci con: </div>' +
			'<div style="float:right"><input type="text" id="findReplaceEis_replace" size="30"/></div>' +
			'<div style="clear:both;float:left">' +
			'<div style="float:right;margin-top:10px;"><input type="button" id="findReplaceEis_ok"  value="OK"/></div>');
		
		
		var box=$("<div id='editBoxEis' style='background-color:#dfdfdf; min-height:10px; display:inline-block;position:fixed; top:0; left:0; z-index:100' ></div>");
		
		if (mw.user.options.get("gadget-barbaforcutanew")==false)  {
			box.resizable();
			$("#content").append(box); 
		}
		else {
			box.css("position","static").appendTo($(".editButtons"));
		}
		
	    
		var qb='<span id="radiobuttons">'+
			'<span class="quality0"><input tabindex="5" title="Pagine_SAL_00%" type="radio" value="0" name="wpQuality"></span>'+
			'<span class="quality2"><input tabindex="6" title="Pagine_SAL_50%" type="radio" value="2" name="wpQuality"></span>'+
			'<span class="quality1"><input tabindex="7" title="Pagine_SAL_25%" type="radio" value="1" name="wpQuality"></span>'+
			'<span class="quality3"><input tabindex="8" title="Pagine_SAL_75%" checked="" type="radio" value="3" name="wpQuality"></span>'+
			'<span id="radioQuality4" class="quality4" style="visibility:hidden;"><input tabindex="9" title="Pagine_SAL_100%" type="radio" value="4" name="wpQuality">&nbsp;&nbsp;</span></span>';

		qb+='<span>&nbsp;&nbsp;'+
			'<button class="baseButton" id="wpPrev" style="display: inline; padding: 1px 2px;" type="button" title="Vai alla pagina precedente" ><small>&lt;</small></button>'+
			'<button class="baseButton" id="wpNext" style="display: inline; padding: 1px 2px;" type="button" title="Vai alla pagina successiva" ><small>&gt;</small></button>'+
			'<button class="baseButton" id="wpSaveStay" style="display: inline; padding: 1px 2px;" type="button" title="Salva le modifiche" ><small>Salva</small></button>'+
			'<button class="baseButton" id="wpSave" style="display: inline; padding: 1px 2px;" type="button" title="Salva le modifiche e apri la pagina successiva" ><small>Salva e procedi</small></button>'+
			'<button class="baseButton" id="wpPreview" style="display: inline; padding: 1px 2px;" type="button" title="Visualizza anteprima" ><small>Anteprima</small></button>'+
			'<button class="baseButton" id="wpWikitext" style="display: none; padding: 1px 2px;" type="button" title="Visualizza anteprima" ><small>Wikitesto</small></button>'+
			'<button class="baseButton" id="copiaUrl" style="display: inline; padding: 1px 2px;" type="button" title="Copia url immagine"><small>Copia url</small></button>'+
			'&nbsp;<span style="font-size:75%; color:#aaa;">Vai a pag: </span>'+
			'&nbsp;<input type="text" id="wpNextPage" title="Pagina successiva" value="" size="4" >'+
			'&nbsp;<input type="text" id="wpComment" value="Ajax eis edit" size="25"></span>'+
			'<img alt="✔" src="//upload.wikimedia.org/wikipedia/commons/thumb/f/fb/Yes_check.svg/15px-Yes_check.svg.png" style="width:px; height:15px;display:none" id="ok_img"/> ';
		$("#editBoxEis").append($(qb));
		
		$("span[class^='quality'] input").click(function() {
				$("#wpComment").val("/* new eis level"+$(this).attr("value")+" */");
			});
		$('#wpNextPage').keyup(function (e) {
		    if (e.keyCode === 13) {
		       	// controllo numero pagina
		       	if ($("#wpNextPage").val()*1>eis.indexLength) {
					$("#wpNextPage").val(eis.indexLength);
				}
			$("#wpNext").click(); //alert('ya!')
		    }
		});
		$("#wpNextPage").dblclick(function(){
			// controllo numero pagina
			if ($("#wpNextPage").val()*1>eis.indexLength) {
				$("#wpNextPage").val(eis.indexLength);
			}
			$("#wpNext").click();
		});
		$("#wpExit").click(function(){
			window.open("/wiki/"+eis.cp.title,"_self"); 
		});
		$("#wpSave").click(function(){
			pageSave(1);
		});
		$("#wpSaveStay").click(function(){
			pageSave(0);
		});
		$("#wpPreview").click(function(){
			// pp(prevPage());
			
			$("#divPreview").css("display","block");
			$("#wpPreview").css("display","none");
			$("#wpWikitext").css("display","inline");
			pagePreview();
			
		});
		$("#wpWikitext").click(function(){
			// pp(prevPage());
	
			$("#divPreview").css("display","none");
			$("#wpPreview").css("display","inline");
			$("#wpWikitext").css("display","none");
				
		});
		$('#copiaUrl').click(function() {
	        navigator.clipboard.writeText('https:'+$('.prp-page-image img').attr('src'));
	        mw.alertMessage("Image URL", "L'indirizzo dell'immagine della pagina è stata caricata negli appunti");
	    });
		$("#wpPreviewSave").click(function(){
			pagePreview();
		});
		$("#wpPrev").click(function(){
			pp(prevPage());
			
		});
		$("#wpNext").click(function(){
			// $("#divPreview").css("display","none");
			pp(nextPage());
		
		});
		//creazione box divPreview
		var divPreview=$("<div>").css({
			"position":"absolute",
			"top":"0",
			"left":"0",
			"width":"100%",
			"height":$(".prp-page-image").css("height"),
			"overflow":"auto",
			"padding":"10px",
			"z-index":"150",
			"background-color":"white",
			"border":"1px solid black",
			"display":"none"
			}).attr("id","divPreview")
			// .dblclick(function() {$("#divPreview").toggle();})
			.append($("<div>").attr("id","previewContent"));
			$("<div>").attr("style",'position:absolute; top:0;right:0;cursor:pointer; z-index:200;')
			.append($('<button class="baseButton" id="wpPreviewExit" style="display: inline; padding: 1px 2px;" type="button" title="Chiudi" ><small>Annulla</small></button>').click(function(){$("#divPreview").toggle();}));

		$(".prp-page-content").css("position","relative").append(divPreview);
			
$('#previewContent').mouseup(function() {
		    var text=$.trim(getSelectedText());
		    
		    // 
		    if (text !== '') {
		    	/* $("#findReplaceEis_box").css("display","block");
		    	$("#findReplaceEis_find").val(text);
		    	$("#findReplaceEis_replace").val(text).focus(); */
		    	$("#inputField").remove();
		    	var s=getSelection();
				var r=s.getRangeAt(0).getBoundingClientRect();
				$("<input>").attr("id","inputField").attr("type","text")
					.css({"position":"fixed","top":r.y-3,"left":r.x,"height":r.height,"width":r.width})
					.val(text)
					.appendTo($(".pagetext"));
				$("#inputField").focus();
				$('#inputField').keyup(function(event) {
					var keycode = event.keyCode || event.which;
					if(keycode == '13') {
						gestisciInput(text);
						
					}
					if(keycode == '27') {
						$("#inputField").remove();
					}
				}).focusout(function(){gestisciInput(text);});
				
		    }
		});
		
function gestisciInput(oldText) {
	var newText=$("#inputField").val();
	if (newText !== oldText) {
		scriviBox(leggiBox().replace(oldText,newText));
	}
	$("#inputField").remove();
	pagePreview();
	
}
		
		eis.baseImg=$(".prp-page-image img").attr("src").match(/(.+page)\d+(-\d+px.+)/);
		// eis.baseImg[1]+[numero pagina]+eis.baseImg[2] è l'url dell'immagine
		// della pagina [numero pagina)]
		// può essere caricato con 
		// $(".prp-page-image img").attr("src",eis.baseImg[1]+211+eis.baseImg[2]);
	}
	function nextPage() {
		/*var np=eis.cp.title.match(/(.+\/)(\d+)$/);
		if (np[2]==eis.indexLength-1) $("#wpNext").css("display","none"); else  $("#wpNext").css("display","inline");
		return np[1]+(np[2]*1+1);
		*/
		var np=eis.cp.title.match(/(.+\/)(\d+)$/);
		return np[1]+$("#wpNextPage").val();
	}
	function prevPage() {
		var np=eis.cp.title.match(/(.+\/)(\d+)$/);
		if (np[2]==2) $("#wpPrev").css("display","none"); else  $("#wpNext").css("display","inline");
		return np[1]+(np[2]*1-1);
	}	
	// splits wiki code into header,body,footer
	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;
	}
	// reads three pages code (current, previous, previous of previous)	
	function pp(pageName) {
		if (pageName===undefined) pageName=mw.config.get("wgPageName");
		pageName=pageName.replace(/_/g," ");
		var pagine={};
		var t=(/(.+\/)(.+)$/).exec(pageName); // t[1]: base  pagina t[2]: numero pagina
		var	t1=t[2]*1-1;
		var	t2=t[2]*1-2;
		eis.t3=t[2]*1+1; // predispongo numero pagina successiva
		console.log(eis.t3,eis.indexLength)
		if (eis.t3>eis.indexLength) eis.t3=t[2]; // controllo che non sia oltre la fine indice
		$("#wpNextPage").val(eis.t3); // imposto il numero pagina successiva in wpNextPage
		
		var p_cor=pageName;
		var p_prec1=t[1]+t1;
		var p_prec2=t[1]+t2;
		console.log(p_prec2,p_prec1,p_cor);
		var api = new mw.Api();
		$("#firstHeading").text("Modifica eis di "+pageName);
		// lettura di tre pagine
		
		api.get( {
		    action: 'query',
		    prop: 'revisions',
			titles:p_prec2+"|"+p_prec1+"|"+p_cor,
			rvprop:"content"
		} ).done( function ( data ) {
			    alex.query=data.query.pages;
			    $.each(data.query.pages, function(index,value) {
					if (alex.query[index].missing!==undefined) 
						pagine[alex.query[index].title]=["","",""]; 
					else 
						pagine[alex.query[index].title]=splitPagina(alex.query[index].revisions[0]["*"]);
			    });
				eis.p_2=[p_prec2,pagine[p_prec2]];
				eis.p_1=[p_prec1,pagine[p_prec1]];
				eis.p_0=[p_cor,pagine[p_cor]];
				alex.p_2=eis.p_2;
				alex.p_1=eis.p_1;
				alex.p_0=eis.p_0;
				testoPag2Prec=alex.p_2[1];
				testoPagPrec=alex.p_1[1];
				
				// settaggi comuni
				eis.cp.basePageName=t[1];
				eis.cp.basePageNum=t[2];
				eis.cp.title=eis.p_0[0];
				
				mw.config.set("wgTitle",eis.cp.title);
				mw.config.set("wgPageName",/.+\//.exec(mw.config.get("wgPageName"))[0]+eis.cp.basePageNum);
				
				// oscuramento next se ultima pagina e prev se prima
				if ( eis.cp.basePageNum >= eis.indexLength) $("#wpNext").css("display","none"); else $("#wpNext").css("display","inline");
				if ( eis.cp.basePageNum == 1) $("#wpPrev").css("display","none"); else $("#wpPrev").css("display","inline");
				
				// modifica link Leggi e Modifica
				if ($("#ca-view a").length===1) {
					eis.cp.linksUrl=$("#ca-view a").attr("href").replace(/\d+$/,eis.cp.basePageNum);
					$("#ca-view a").attr("href",eis.cp.linksUrl);
					$("#ca-edit a").attr("href",eis.cp.linksUrl);
				}
				

				var urlpc=/.+\//.exec($("#ca-nstab-page a").attr("href"))[0]+eis.cp.basePageNum;
				$("#ca-nstab-page a").attr("href",urlpc).attr("target","_blank");
				urlpc=/.+\//.exec($("#ca-talk a").attr("href"))[0]+eis.cp.basePageNum;
				$("#ca-talk a").attr("href",urlpc).attr("target","_blank");
				if ($("#croptool").length>0) {
					eis.cp.croptool=$("#t-cropNew a").attr("href").replace(/\d+$/,eis.cp.basePageNum);
					$("#t-cropNew a").attr("href",eis.cp.croptool);
				}
				var urlImg=$(".prp-page-image img").attr("src").match(/(.+page)(\d+)(-.+)/);
				eis.cp.imageUrl=urlImg[1]+eis.cp.basePageNum+urlImg[3];
				
				// assegno valori alle variabili globali testoPagPrec e testo2PagPrec per renderli visibili a autoPt e autoRi7
				testoPagPrec=eis.p_1[1];
				testo2PagPrec=eis.p_2[1];
				$("#radioQuality4").css("visibility","hidden");
				$(".prp-page-image img").attr("src",eis.cp.imageUrl);
				/* qui inserita routine per caricare l'immagine nel canvas OpenSeadragon
				Critica l'aggiunta del prefisso https: alla stringa url immagine
				*/
				mw.hook( 'ext.proofreadpage.osd-viewer-ready' ).add( function ( viewer ) {
				    // Can use viewer or mw.proofreadpage.viewer - they're the same
				    viewer
				        .addSimpleImage( {
				            url: 'https:'+eis.cp.imageUrl
				        } );
				} );
				if (eis.p_0[1].toString()===",,") {
					// caso pagina corrente non esistente
					// leggo la pagina...
					$.get( mw.config.get("wgServer")+"/w/index.php?title="+normUrl(mw.config.get("wgPageName"))+"&action=edit&redlink=1", function( data ) {
						$("#wpTextbox1").val($("#wpTextbox1",$(data)).val());
						
						
						eis.cp.header="";
						eis.cp.footer="";
						$("#wpHeaderTextbox").val(eis.cp.header);
						$("#wpFooterTextbox").val(eis.cp.footer);
						
						// eseguo autoRi, Rv, postOcr, regex
						// preOCR();
						$("#buttonautoRi").click();
                        $("#buttonpostOCR").click();
						// $("#button6").click();
                        $("#buttonRunregex").click();
						eis.p_0[1][1]= $("#wpTextbox1").val();
						eis.cp.user=mw.config.get("wgUserName");
						eis.cp.level="1";
						$("#radiobuttons input[value='"+eis.cp.level+"']").click();
						pagePreview();
					});
				} else {
					// caso pagina esistente
					eis.cp.user=eis.p_0[1][0].match(/user=\"([^"]*)\" \/>/)[1];
					eis.cp.level=eis.p_0[1][0].match(/level=\"(\d+)\" /)[1];
					eis.cp.header=$.trim(eis.p_0[1][0].replace(/<noinclude\><pagequality.+?>/,"").replace("</noinclude>",""));
					eis.cp.footer=$.trim(eis.p_0[1][2].replace("<noinclude>","").replace("</noinclude>",""));
					$("#wpHeaderTextbox").val(eis.cp.header);
					$("#wpFooterTextbox").val(eis.cp.footer);
					$("#wpTextbox1").val(eis.p_0[1][1]);
					
					// if level=3 and user is another one, or if level=4 display radiobutton4
					if ( (eis.cp.level==="3" && eis.cp.user!==mw.config.get("wgUserName")) || eis.cp.level==="4") $("#radioQuality4").css("visibility","visible");
					
					$("#radiobuttons input[value='"+eis.cp.level+"']").click();
					pagePreview();
				}
	
		});
		$(".prp-page-image img").css("top","0");
		$("#wpTextbox1").scrollTop(0);
	};
	function chiudiEditBox () {
		$("#sfondoeis").toggle();
	}
	function pageBuild() {
		var template= '<noinclude><pagequality level="#LEVEL#" user="#USER#" />#HEADER#</noinclude>' + 
		'#BODY#<noinclude>#FOOTER#\n</noinclude>';
		var wikicode= template.replace("#HEADER#",$("#wpHeaderTextbox").val())
			.replace("#BODY#",$("#wpTextbox1").val())
			.replace("#FOOTER#",$("#wpFooterTextbox").val());
		if (eis.cp.level ===$("input:checked","#radiobuttons").val()) {
			 wikicode=wikicode.replace("#LEVEL#",eis.cp.level).replace("#USER#", eis.cp.user);
		} else {wikicode=wikicode.replace("#LEVEL#",$("input:checked","#radiobuttons").val())
		   	    	.replace("#USER#", mw.config.get("wgUserName"));
		}

		return wikicode;
	}
	
	
	function pageSave(azione) {
		var wikicode=pageBuild();
		new mw.Api().postWithToken( 'edit', {
			action: 'edit',
			title: eis.cp.title,
			summary:$("#wpComment").val(),
			text: wikicode,
		}).done(function( data ) {
	        if ( data && data.edit && data.edit.result === 'Success' ) {
				$("#ok_img").toggle();
				setTimeout(function (){
					$("#ok_img").toggle();
				}, 500);
				if (azione==1 && eis.cp.basePageNum < eis.indexLength) $("#wpNext").click();
				if (azione==-1) $("#wpPrev").click();
			} else {
				alert("Errore nel salvataggio della pagina");
			}
		});
	}
	function pagePreview() {
		// toggleButton generico (nasconde parent())
		/*	var toggleButton=$('<img>')
		    .attr("src","//upload.wikimedia.org/wikipedia/commons/f/f8/Tooltip-CloseButton.png") 
		    .attr("style",'position:absolute; top:0;right:0;cursor:pointer; z-index:200;')
			.click(function(){$(this).parent().toggle();}); 
		*/
		//caricamento preview
		var wikicode=pageBuild();
		// $("#divPreview").toggle();
		$.ajax({
         	url: mw.util.wikiScript( 'api' ),
        	data: {
            	format: 'json',
            	action: 'parse',
				// contentmodel: 'proofread-page',
				title:eis.cp.title,
				summary: "ajax preview",
            	text: wikicode,
            	time: $.now()
            	},
        	dataType: 'json',
        	type: 'POST',
        	success: function( data ) { 
        		if ( data && data.parse ) {
					
					$("#previewContent").html($(data.parse.text["*"]));

            	} else if ( data && data.error ) {
                		alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
            			} else {
                			alert( 'Error: Unknown result from API.' );
						}
        		},
        		error: function( xhr ) {
        			alert( 'Error: Request failed.' );
			}
    	});
	}
	mw.pagePreview=pagePreview;
	/* 
	$("#findReplace_box input[value='OK']").click(function() {
	if($("#divPreview")==="block") {
	pagePreview();
	}
    }) */

function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection().toString();
    } else if (document.selection) {
        return document.selection.createRange().text;
    }
    return '';
}

})(jQuery,mw);