User:Samwilson/eis.js

/* Edit In Sequence, version 0.0 ottobre 2016 Alex brollo

Logics: 1. disable navigation and save/preview buttons 2. load a small new navigation + level setting tool 3. use normal edit boxes uploading wikicode and saving edited wikicode from them by ajax statements

var eis={}; eis.cp={}; ( function ( $, mw ) {	var sysMessages = [ 'eis-button-label' ];

/**	 * The initialisation function, run on every load. Adds the activation button * to the toolbar if we're currently editing or previewing in the Page * namespace. */	function init { var isPage, useOldToolbar, useBetaToolbar, toolbarLib; mw.loader.using( 'user.options', function {			isPage = mw.config.get( 'wgCanonicalNamespace' ) === 'Page';			useOldToolbar = mw.user.options.get( 'showtoolbar' ) === 1;			useBetaToolbar = mw.user.options.get( 'usebetatoolbar' ) === 1;			if ( isPage && ( useOldToolbar || useBetaToolbar ) ) {				toolbarLib = useBetaToolbar ? 'ext.wikiEditor' : 'mediawiki.toolbar';				mw.loader.using( [ 'mediawiki.api', toolbarLib ], function  { mw.loader.load("jquery.ui"); new mw.Api.loadMessagesIfMissing( sysMessages ).then( customizeToolbar( useBetaToolbar ) ); } );			}		} );	}

/**	 * Add the OCR button to the toolbar. This is called in run, and doesn't	 * need to check anything about whether we need to add the button. *	 * @param {boolean} useBeta Whether the WikiEditor toolbar should be used. */	function customizeToolbar( useBeta ) {

// Add old-style toolbar button. if ( ! useBeta && mw.toolbar ) { mw.toolbar.addButton( {				//imageFile: 'https://upload.wikimedia.org/wikipedia/commons/c/ca/GoogleOcr_toolbar_button.png',				speedTip: mw.message( 'eis-button-label' ),				imageId: 'EisButton'			} ); }

// Add new-style WikiEditor toolbar button. if ( useBeta ) { $( document ).ready( function {				var buttonDetails = {					type: 'button',					icon: 'https://upload.wikimedia.org/wikipedia/commons/3/3a/Toolbaricon_bold_S.png',					labelMsg: 'eis-button-label',					action: { type: 'callback', execute: activate }				};				var button = {					section: 'proofreadpage-tools',					group: 'other',					tools: { 'eis': buttonDetails }				};				$( "#wpTextbox1" ).wikiEditor( 'addToToolbar', button );			} ); }	}

/**	 * Activate EiS when clicking the toolbar button. */	function activate { creaEis; pp; }

// initiaizing function, it disables some buttons, builds preview box, build action buttons function creaEis { // disabilitazioni $("#ca-proofreadPagePrevLink a, #ca-proofreadPageNextLink a").remove; $("#wpSave, #wpPreview, #wpDiff").remove; $(".mw-summary, .editCheckboxes").remove; $("#ca-eis").remove;

//$(' ').appendTo($("#content")); var box=$(" "); if (mw.user.options.get("gadget-barbaforcutanew")===null) $("#content").append(box); else box.css("position","static").appendTo($(".editButtons"));

var qb=' '+ '  '+ '  '+ '  '+ '  '+ '   ';

qb+=' '+ ' < '+ ' > '+ ' Save and go on '+ ' Save after preview '+ ' Preview '+ ' Exit '+ '  '; $("#editBox").append($(qb));

$("#wpExit").click(function{			window.open("/wiki/"+eis.cp.title,"_self"); 		}); $("#wpSave").click(function{			pageSave;		}); $("#wpPreview").click(function{			pagePreview;		}); $("#wpPreviewSave").click(function{			pagePreview;		}); $("#wpPrev").click(function{			$("#divPreview").css("display","none");			pp(prevPage);		}); $("#wpNext").click(function{			$("#divPreview").css("display","none");			pp(nextPage);		}); //creazione box divPreview var divPreview=$(" ").css({			"position":"absolute",			"top":"20px",			"left":"100px",			"width":"580px",			"height":"700px",			"overflow":"scroll",			"padding":"20px",			"z-index":"150",			"background-color":"white",			"border":"1px dotted black",			"display":"none"			}).attr("id","divPreview") .append($(" ").attr("id","previewContent"));

$("#content").append(divPreview); $("#divPreview").draggable; var x=$(" ").attr("style",'position:absolute; top:0;right:0;cursor:pointer; z-index:200;') .append($(' Exit ').click(function{$("#divPreview").toggle;})) .append($("#wpSave").clone(true)); x.appendTo($("#divPreview")); 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+)$/);		return np[1]+(np[2]*1+1);	}	function prevPage {		var np=eis.cp.title.match(/(.+\/)(\d+)$/);		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(" ") + 12);		testo[2] = tpp.substring(tpp.lastIndexOf(" "));		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");		eis.p_0=[];		eis.p_1=[];		eis.p_2=[];		var p=[];		var t=(/(.+\/)(.+)$/).exec(pageName);		var	t1=t[2]*1-1;		var	t2=t[2]*1-2; var api = new mw.Api; api.get( {		   action: 'query',		    prop: 'revisions',			titles:t[1]+t2+"|"+t[1]+t1+"|"+t[1]+t[2],			rvprop:"content"		} ).done( function ( data ) {			    $.each(data.query.pages, function(index,value) { try {p.push([value.title,value.revisions[0]["*"]]);} catch(err) {p.push([value.title,""]);} });				eis.p=p;				try {           		eis.p_2=[p[0][0],splitPagina(p[0][1])];				}				catch(err) {eis.p_2=["",],[],[ ];}				try {				    eis.p_1=[p[1][0],splitPagina(p[1][1])];				}				catch(err) {eis.p_1=["",],[],[ ];}					try {					eis.p_0=[p[2][0],splitPagina(p[2][1])];					eis.cp.title=eis.p_0[0];					var np=eis.cp.title.match(/(.+\/)(\d+)$/);					eis.cp.basePageName=np[1];					eis.cp.basePageNum=np[2];					var urlImg=$(".prp-page-image img").attr("src").match(/(.+page)(\d+)(-.+)/);					eis.cp.imageUrl=urlImg[1]+eis.cp.basePageNum+urlImg[3];					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(//,"").replace(" ",""));					eis.cp.footer=$.trim(eis.p_0[1][2].replace(" ","").replace(" ","").replace(" ",""));					$("#wpHeaderTextbox").val(eis.cp.header); $("#wpFooterTextbox").val(eis.cp.footer); $("#wpTextbox1").val(eis.p_0[1][1]); // assigning values to two global variables for compatibility with some it.source tools testoPagPrec=eis.p_1[1]; testo2PagPrec=eis.p_2[1]; alex.p_0=eis.p_0; alex.p_1=eis.p_1; alex.p_2=eis.p_2; $("#radioQuality4").css("display","none"); // 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("display","inline"); $("#radiobuttons input[value='"+eis.cp.level+"']").click; $(".prp-page-image img").attr("src",eis.cp.imageUrl); $("#firstHeading").text("Modifica eis di "+eis.cp.title); }				catch(err) { eis.p_0=["",],[],[ ]; console.log("Loading exception:"); console.log(err); }						} );	}	function chiudiEditBox {		$("#sfondoeis").toggle;	}	function pageBuild {		var template= ' <pagequality level="#LEVEL#" user="#USER#" />#HEADER# ' + 		'#BODY# #FOOTER#\n ';		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 { 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' ) {				console.log("OK, pagina " + eis.p_0[0] + "salvata");				$("#wpNext").click;			} else {				alert("Errore nel salvataggio della pagina");			}		}); }	function pagePreview {

//caricamento preview var wikicode=pageBuild; $("#divPreview").toggle; $.ajax({        	url: mw.util.wikiScript( 'api' ),        	data: {            	format: 'json',            	action: 'parse',				contentmodel: 'proofread-page',				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.' ); }   	});	}

init; } )( jQuery, mw );