User:Alex brollo/corners.js

From Wikisource
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
importStylesheet("User:Alex brollo/corners.css");
mw.loader.load("jquery.ui");newTemplate={};
testo=[];

function corners() {

	inizializzaNewTemplate(); // nell'oggetto newTemplate vengono caricati i valori di default
	inizializzaTesto1();      // in testo si carica la selezione e si aggiorna newTemplate con eventuali valori caricati
	creaBox();                // si crea il box html sulla base di newTemplate 
	preview();                // si allineano box, newtemplate, testo[1] e previewArea
    
}

function inizializzaNewTemplate() {
	newTemplate=JSON.parse(
   '[{"0":"Ritaglio", "type":"", "file":"'+wgTitle.split("/")[0]+
   '", "page":"'+wgTitle.split("/")[1]+
   '", "thumb":"600px", "width":"600px", "cclass":"", "float":"left", "margin-left":"1px", "margin-right":"1px", "margin-top":"1em", "margin-bottom":"1em", "wHeight":"100px", "wWidth":"100px", "wLeft":"20px", "wTop":"20px", "clear":"", "caption":"", "mleft":"", "indent":"", "tstyle":"", "talign":"", "alt":""}, ["0", "type", "file", "page", "thumb", "width", "cclass", "float", "margin-left", "margin-right", "margin-top", "margin-bottom", "wHeight", "wWidth", "wLeft", "wTop", "clear", "caption", "mleft", "indent", "tstyle", "talign", "alt"]]');
   }

function inizializzaTesto1() {
	testo=['','',''];
        if (wgAction=="edit" || wgAction=="submit") testo=selection();
	if (testo[1]==="") return false;
	testo[1] = testo[1].replace(/(\{\{FreedImg\/crop|\{\{Ritaglio|\{\{Crop)/gi, "{{Ritaglio");
    var fi = find_stringa(testo[1], "{{Ritaglio", "}}", 1, "{{");
    if (testo[1] !== fi) {testo[1]=""; return false;}
	
	// caricamento dati in newTemplate
	var tpl = parseTemplate("Ritaglio", fi);
   // aggiornamento di newTemplate con i valori letti
	for (i = 1; i < tpl[1].length; i += 1) {
      // nome del parametro
      parametro = tpl[1][i];
      newTemplate[0][parametro] = tpl[0][parametro];
     }
	 return true;
}


// legge i valori dei due corners (leggiCorners); aggiorna newTemplate; poi aggiorna testo[1]; infine aggiorna previewArea
function preview(opzione) {
    leggiCorners();
	aggiornaTesto1(opzione);
    $("#previewArea").val(testo[1]);
}

// trasforma una stringa tipo 200px in un numero 200
function depix (pixel) {
    return pixel.replace("px","")*1;
}
 
function leggiCorners() {
    var top = [cornerTop[0].offsetTop, cornerTop[0].offsetLeft];
    var bottom = [cornerBottom[0].offsetTop + 20, cornerBottom[0].offsetLeft + 20];
	newTemplate[0].wTop=cornerTop[0].offsetTop+"px";
	newTemplate[0].wLeft=cornerTop[0].offsetLeft+"px";
	newTemplate[0].wWidth=(bottom[1]-top[1])+"px";
	newTemplate[0].wHeight=(bottom[0]-top[0])+"px";
        newTemplate[0]["margin-right"]=(421 - bottom[1] + top[1]) / 2 + "px";
        newTemplate[0]["margin-left"]=(421 - bottom[1] + top[1]) / 2 + "px";
        newTemplate[0].width=$("#imgContainer").css("width"); // aggiungo per predisporre il redim

	}
	
function aggiornaTesto1(opzione) {
   var t = "";
   var tpl=newTemplate;
   if (typeof(opzione)==="undefined") opzione=2; // default centrato flottante
   // 1=centrato 2=centrato flottante 3=a destra 4= a sinistra
   if (opzione==1) {
      tpl[0].float="";
	  tpl[0]["margin-right"]="";
	  tpl[0]["margin-left"]="";
	  }
	if (opzione==3) {
      tpl[0].float="right";
	  tpl[0]["margin-right"]="0em";
	  tpl[0]["margin-left"]="1em";
	  }
	if (opzione==4) {
      tpl[0].float="left";
	  tpl[0]["margin-right"]="1em";
	  tpl[0]["margin-left"]="0em";
	  }
   $.each(tpl[1], function(indice, valore) {
      if (indice !== 0 && $.trim(tpl[0][valore]) !== "") t += " | " + valore + " = " + tpl[0][valore] + "\n";
   });
   t = "{{" + tpl[0]["0"] + "\n" + t + "}}\n";
   t = t.replace(/\n\s\|\s\d*\s=\s/g, "\n | ");
   testo[1]=t;
}

//ridisegna il quadrato compreso tra i due angoli, in modo da tenerlo sempre allineato
function redrawCropArea() {
 
	$('#cropArea').css({
		top: 	$('#cornerTop').css('top'), 
		left: 	$('#cornerTop').css('left'),
		width:	( depix($('#cornerBottom').css('left')) - depix($('#cornerTop').css('left')) +20) + 'px',
		height:	( depix($('#cornerBottom').css('top')) - depix($('#cornerTop').css('top')) +20) + 'px' });
}
function creaBox() {
   var imgSmall = $("#pr_container img").eq(0).clone();
   imgSmall.css("width", "inherit");
   var buttonTop=[depix(newTemplate[0].wTop),depix(newTemplate[0].wLeft)];
   var buttonBottom=[depix(newTemplate[0].wHeight)+buttonTop[0]-20,depix(newTemplate[0].wWidth)+buttonTop[1]-20];
   
   cornerTop = $(
      '<div id="cornerTop" style="border-left-width: 2px; border-left-style: solid; border-left-color: red; border-top-width: 2px; border-top-style: solid; border-top-color: red; position: absolute; z-index: 100; width: 20px; height: 20px; top: '+
	  buttonTop[0]    +	  'px; left: '   + 	  buttonTop[1]   +  'px;" >');
   cornerBottom = $(
      '<div id="cornerBottom" style="border-right-width: 2px; border-right-style: solid; border-right-color: red; border-bottom-width: 2px; border-bottom-style: solid; border-bottom-color: red; position: absolute; z-index: 100; width: 20px; height: 20px; top: '+buttonBottom[0]+'px; left: '+buttonBottom[1]+'px;" class="ui-draggable"></div>');

//quadrato tratteggiato tra i due angoli
   cropArea = $('<div id="cropArea" style="position: absolute; border: 1px dashed black;"></div>');
   
   var mainCropBox = $(
      '<div id="mainCropBox" class="uls-menu" style="display: block; position: fixed; z-index: 9999; top: 0px; left: 200px; height: 600px; width: 900px; overflow: auto; border: 2px solid red;background-color:white; ">' +
      '<div class="row"><span id="mainCropBox-close" class="icon-close" onclick="exitCursors()"></span></div>'+
      '<table style="border-spacing: 0px;">' +
      '<tr>' +
      '<td>' +
      '<div style="height: 600px;overflow: auto; position:relative;">' +
      '<div id="imgContainer" style="width: '+newTemplate[0].width+';">' +
      '</div>' +
      '</div>' +
      '</td>' +
      '<td width="300px">' +
	  '<button type="button" title="Centrato" onclick="preview(1)" class="button blue"><small>Centrato</small></button>' +
	  '<button type="button" title="Centrato flottante" onclick="preview(2)" class="button blue"><small>Centrato flottante</small></button>' + '<br/>' +
	  '<button type="button" title="A destra" onclick="preview(3)" class="button blue"><small>A destra</small></button>' +
	  '<button type="button" title="A sinistra" onclick="preview(4)" class="button blue"><small>A sinistra</small></button>' + '<br/>' +
	  '<br /><button type="button" title="Ridimensiona" onclick="ridimensiona()" class="button blue"><small>Ridimensiona</small></button>' +
      '<textarea rows="20" cols="30" style="margin-top: 2px; margin-bottom: 2px; height: 340px;" id="previewArea" wrap="hard"></textarea><br/>' +
      '<button type="button" title="Chiudi e esporta i dati" onclick="data()" class="button blue"><small>Esporta il template</small></button>' +
      '<button type="button" title="Chiudi senza esportare i dati" onclick="exitCursors()" class="button"><small>Annulla</small></button>' +
      '</td>' +
      '</tr>' +
      '</table>' +
      '</div>');

   $("#mainCropBox").remove(); //rimuovi se per caso era gia' aperto
   $("body").append(mainCropBox);
   var td1 = $("#mainCropBox td div div").eq(0);
   td1.append(cornerTop).append(cornerBottom).append(cropArea).append(imgSmall);
   $("#cornerTop").draggable({
      containment: "parent",
      scroll: false,
      drag: function(event, ui) { preview(); redrawCropArea(); }
   });
   $("#cornerBottom").draggable({
      containment: "parent",
      scroll: false,
      drag: function(event, ui) { preview(); redrawCropArea(); }
   });
   
   redrawCropArea();
}

// ridimensiona
function ridimensiona() {
	var nuovaWidth=prompt("Ridimensiona il valore attuale dell'immagine",$("#imgContainer").css("width"));
	// però adesso fallo..... :-)
	ratio=depix(nuovaWidth)/depix($("#imgContainer").css("width"));
	$("#imgContainer").css("width",depix($("#imgContainer").css("width"))*ratio+"px"); 
	
	$("#cornerTop").css("left",depix($("#cornerTop").css("left"))*ratio+"px"); $("#cornerTop").css("top",depix($("#cornerTop").css("top"))*ratio+"px"); $("#cornerBottom").css("top",depix($("#cornerBottom").css("top"))*ratio+"px"); $("#cornerBottom").css("left",depix($("#cornerBottom").css("left"))*ratio+"px"); 
	preview();
	redrawCropArea();
}

// uscita senza salvare

function exitCursors() {
   // delete newTemplate;
   // delete testo;
   $("#mainCropBox").remove();
}

function data() {
	testo[1]=$.trim($("#previewArea").val());
	scriviBox(testo.join(""));
	// delete newTemplate;
	// delete testo;
	$("#mainCropBox").remove();

}





function newRewriteTemplate(x) {
   var testo = "";
   $.each(x[1], function(indice, valore) {
      if (indice !== 0 && $.trim(x[0][valore]) !== "") testo += " | " + valore + " = " + x[0][valore] + "\n";
   });
   testo = "{{" + x[0]["0"] + "\n" + testo + "}}\n";
   testo = testo.replace(/\n\s\|\s\d*\s=\s/g, "\n | ");
   $("#previewArea").val(testo);
}
// nuova funzione per caricare da textarea un template Ritaglio o sinonimi, eseguirne il parsing, 
// aggiornare newTemplate e rappresentarlo in previewArea 

function newredim() {
   // analisi selezione
   
   testo[1] = testo[1].replace(/(\{\{FreedImg\/crop|\{\{Ritaglio|\{\{Crop)/gi, "{{Ritaglio");
   if (testo[1]!== "") {
   
   }
   var fi = find_stringa(testo[1], "{{Ritaglio", "}}", 1, "{{");
   if (testo[1] !== fi) {
      return "Errore: la selezione dev'essere vuota o contenere esattamente\nil template Ritaglio o sinonimo. Ripetere.";
   }
   // caricamento dati in newTemplate
   var tpl = parseTemplate("Ritaglio", fi);
   // aggiornamento di newTemplate con i valori letti
   for (i = 1; i < tpl[1].length; i += 1) {
      // nome del parametro
      parametro = tpl[1][i];
      newTemplate[0][parametro] = tpl[0][parametro];
   }
   // aggiornamento previewArea
   newRewriteTemplate(newTemplate);
   return testo;

}

// vecchia funzione per il ridimensionamento diretto del template in textarea

function redim() {
   var testo = selection();
   var fi = find_stringa(testo[1], "{{FreedImg/crop", "}}", 1, "{{");
   var tpl = parseTemplate("FreedImg/crop", fi);
   var ratio = prompt("Ratio incremento/decremento (base 1):\n");
   tpl[0].width = redim1(tpl[0].width, ratio);
   tpl[0].wHeight = redim1(tpl[0].wHeight, ratio);
   tpl[0].wWidth = redim1(tpl[0].wWidth, ratio);
   tpl[0].wLeft = redim1(tpl[0].wLeft, ratio);
   tpl[0].wTop = redim1(tpl[0].wTop, ratio);
   var newTpl = rewriteTemplate(tpl);
   testo[1] = testo[1].replace(fi, newTpl);
   scriviBox(testo.join(""));
}

function redim1(testo, ratio) {
   var testo = (Math.round(testo.replace("px", "") * ratio)) + "px";
   return testo;
}


$(document).ready(function() {
   if (wgCanonicalNamespace === "Page") { //  && (wgAction === "edit" || wgAction === "submit")) {
      $("#p-tb ul").append($('<li id="t-crop"><a href="javascript:corners()">Ritaglio delle immagini</a></li>'));
   }
});