Utente:Samuele Papa/common.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)
  • Internet Explorer / Edge: tieni premuto il tasto Ctrl e fai clic su Aggiorna, oppure premi Ctrl-F5
  • Opera: premi Ctrl-F5.
/**
* Pagina di prova per l-implementazione di TemplateScript
* Linee guida:
* - Tutti i caratteri wiki vanno escaped, aggiungendo una backslash (\) prima del carattere speciale, ad esempio, \~\~\~\~
*	per impedire che il software wiki li trasformi nel testo effettivo, nel nostro caso la firma.
* -
* Namespaces:
* 3 - Discussione Utente
* 108 - Edit Pagina
*/
/**
 * TemplateScript adds configurable templates and scripts to the sidebar, and adds an example regex editor.
 * @see https://meta.wikimedia.org/wiki/TemplateScript
 * @update-token [[File:pathoschild/templatescript.js]]
 */
 //Variabile globale per tutti gli script
var wikisource = wikisource || {};
wikisource={
	fooo : function(){
		return 'funzione privata accessibile all\'interno del metodo';
	}
}
wikisource.templatescript = wikisource.templatescript || {};
//Sottoclasse statica
wikisource.templatescript=(function(){
	var bottoneria={};
	var classic={};
	console.log(wikisource.fooo())
	//Funzioni private
	
	
	//Funzioni pubbliche
	classic.marcaNote=function(editor){
		editor.replaceSelection(function(selected) {
			return selected + '<sup>nota</sup>';
		});
	}
	
	//Tutto quello dentro a questo array sarà pubblico, il resto è privato e non accessibile dall'esterno
	return {
		bottoneria:bottoneria,
		classic: classic
	};
})();
console.log(wikisource);
//A first draft per sostituire i bottoni, le decine di bottoni della bottoneria e mantenere lacreazione di nuovi user-friendly (il più possibile)
var button = (function(WS){
	//Constructor, props is an array of properties
	Button = function(props){
		var _props = {
			name: "Bottone",
			callback: function(data){
				console.log("Default callback function, here is all the data available:");
				console.log(data);
			}
		}
		//Custom properties
		for(var prop in props){
			if(prop in _props){
				_props[prop] = props[prop];
			}
		}
	}
	return Button;
})(wikisource);



$.ajax('//tools-static.wmflabs.org/meta/scripts/pathoschild.templatescript.js', { dataType:'script', cache:true }).then(function() {
	pathoschild.TemplateScript.library.define({
		key: 'wikisource.proofreading',
		name: 'Strumenti per la rilettura',
		url: '//en.wikisource.org/wiki/Wikisource:TemplateScript#Proofreading',
		description: 'Preso da en wikisource, adattamento per i tool',
		categories: [
			{
				name: 'Page tools',
				scripts: [
					{ key: 'add-header', name: 'Add header', script: function(editor) { addPageHeader(editor); }, forNamespaces: 'page' },
				]
			}
		]
	});
	/**
 	* Add a template to a button box fixed to the bottom of the page. This implementation ignores the 'category' field.
 	* @param {Template} template The template for which to create an entry.
 	* @param {TemplateScript} instance The script instance.
 	* @returns the generated item.
 	*/
	pathoschild.TemplateScript.addRenderer('buttonbox', function(template, instance) {
		// build the button box
		var bar = $('#newtattoo');
		if(!bar.length) {
			mw.util.addCSS(
				  '#newtattoo { position:fixed;bottom:0; right:0; background-color:white; border: 1px solid; border-color:#F0F0F0; z-index:1500; }'
				+ '#newtattoo button { display:inline; font-size:small; }'
			);
			bar = $('<div>')
				.attr({ id: 'newtattoo', align: 'right' })
				.appendTo(mw.user.options.get('skin') === 'modern' ? '#mw_content' : '#content');
		}
		// build tool button
		return $('<button>')
			.attr({ title: template.tooltip })
			.append(template.name)
			.append(template.accessKey ? $('<small>').addClass('ts-shortcut').append(template.accessKey) : null)
			.click(function() { instance.apply(template.id); })
			.appendTo(bar);
	});

	/**
	 * Aggiunge il template di benvenuto alla fine della pagina. Scrive come oggetto 'Benvenuto!'
	 * Agisce solo nelle pagine con namespace=3, come quelle di discussione utente
	 */
	pathoschild.TemplateScript.add([
		{ name: 'Benvenuto', template: '\{\{Benvenuto\}\} \~\~\~\~', position: 'after', editSummary: 'Benvenuto!', forNamespaces: 'discussioni utente', renderer: 'buttonbox' }
	]);
	

	/**
	 * Titoletti all'interno del testo in piccolo, centrato corsivo
	 */
	pathoschild.TemplateScript.add({
		name:'Frammezzi Bibbia',
		script: function(editor){
			editor.replaceSelection(function(selected) {
				return '{'+'{Centrato|<small>\'\'' + selected + '\'\'</small>}}';
			});
		}
	});
	/**
	 * Aggiunge un link sulla toolbar per vedere il contesto in console
	 */
	pathoschild.TemplateScript.add({
		name:'Debugger',
		script: function(editor){
			console.log(editor);
		}
	});
	pathoschild.TemplateScript.add({
		name:'Note in Bibbia',
		script: function(editor){
			var MAINTEXT = editor.get()
			var notes = MAINTEXT.replace(/[\s\S]+<!-- note -->([\s\S]+)<!-- fine note -->/g,'$1')
			
			var list = notes.split(/\n+/);
			var output = ""
			for(var a in list){
				//edge cases
				if(list[a] == "")
					continue;
				output +="\n <ref>"
				var caps = list[a].split(';');
				//in the [0] there will always be the book, needs to be 
				//stored and removed
				var curBook = ""
				var curCap = ""
				var curVersetto = ""
				
				console.log(caps)
				
				if(/\{\{BibLink\|/.test(caps[0])){
					//There is already a biblink created
					caps[0] = caps[0].replace(/[^\|]+\|/,"") //removes BibLink|
					curBook = caps[0].match(/[^\|]+/)[0];
					caps[0] = caps[0].replace(/[^\|]+\|/,"") //removes whatever|
					//curCap = caps[0].match(/[^\|]+/)[0];
					caps[0] = caps[0].replace(/\|/,". ")// replaces | with ". " because it's a chapter
					caps[0] = caps[0].replace(/\}\}/,"")//removes remaining }}
					// all this processing is needed in order not to remove
					//too much information (i.e. all the chapters, versetti etc)
				}else{
					curBook = caps[0].match(/[0-9]*\s*[A-Za-z]+/)[0];
					caps[0] = caps[0].replace(/[0-9]*\s*\D+/,"")
					//curCap = caps[0].match(/[0-9]+/);
				}
				
				for(var i in caps){
					curCap = caps[i].match(/[0-9]+/);
					caps[i] = caps[i].replace(/[0-9]+\.*\s*/,"")
					
					var versetti = caps[i].split(",");
					console.log(versetti)
					for(var j in versetti){
						
						curVersetto = versetti[j].match(/[0-9]+/);
						if(j>0){
							if(curVersetto == null){
								curVersetto = versetti[j].match(/[a-zA-z]+/)
								output+=", "+curVersetto;
								continue;
							}
						}
						//output += "{"+"{BibLink|" + curBook + "|" + curCap + "|" + curVersetto + "}}";
						if(j>0 && i>0){
							output+="; " + "{"+"{BibLink|" + curBook + "|" + curCap + "|" + curVersetto + "|" +curCap + ". "  + curVersetto  + "}}";
						}else if(j>0 && i==0){
							output+=", " + "{"+"{BibLink|" + curBook + "|" + curCap + "|" + curVersetto + "|"  + curVersetto  + "}}";
						}else if(j == 0 && i> 0){
							output+="; " + "{"+"{BibLink|" + curBook + "|" + curCap + "|" + curVersetto + "|"  +curCap + ". "  + curVersetto  + "}}";
						}else{
							output+= "{"+"{BibLink|" + curBook + "|" + curCap + "|" + curVersetto + "}}";
						}
						
					}
					
					console.log(caps[i]);
				}
				output +="</ref>"	
			}
			
			console.log(output);
			editor.replace(/<!-- note -->([\s\S]+)<!-- fine note -->/g,output);
		}
	});
	/**
	 * Converte le virgolette "" in virgolette “”
	 * TODO: 	tis but a simple version
	 * 			Per semplificare ho ricreato lo script da zero, quindi
	 * 			probabilmente non ho considerato decine di casi particolari
	 * 			Segnalare questi casi così possiamo implementarli
	 * */
	pathoschild.TemplateScript.add({
	name:"Virgolette tipografiche",
	script: function(editor) {
		var vs,vc,val,open;
		vs = "“";
		vc = "”";
		val = editor.get();
		var norms = val.match(/\"/g);
		var l = norms.length;
		open = true;
		while(editor.get().indexOf('\"') != -1){
			if(open){
				editor.replace('\"',vs);
				open = false;
			}else{
				editor.replace('\"',vc);
				open = true;
			}
		}
		console.log(norms)
		if(norms.length%2!==0){
			alert("Il numero di virgolette era dispari")
		}
		//editor.replace("")
	}});
	/**
	 * Marca la posizione di una nota all'interno della pagina
	 * 
	 * */
	pathoschild.TemplateScript.add({
	name:"Marca nota",
	script: wikisource.templatescript.classic.marcaNote
	});
	/**
	 * Sposta tutte le note a pie di pagina sostituendole con i marcatori posti lungo il testo
	 *
	 **/
	pathoschild.TemplateScript.add({
	name:"spostamento note",
	script: function(editor) {
			var val = editor.get();
			console.log(val);
			//E' tutto l'opposto di efficiente, però funzia in teoria
			var notes=val.match(/(<ref)(?!.*follow).*(<\/ref>)/g);
			if (val.indexOf("<sup>nota</sup>") === -1) { // note in posizione regolare
				for (i = 0; i < notes.length; i += 1) {
					editor
						.replace(notes[i], "<sup>nota</sup>")
						.append('\n' + notes[i]);
				}
			}else{
				refs = count(val, "<sup>nota</sup>");
				if (notes.length != refs) { // verifica congruenza
					alert("ATTENZIONE: ci sono " + refs + " segnaposti <br /> ma " + notes.length + " note. Controllare!");
					return;
				}
				
				editor.replace(/\n<ref/g, "<ref");
				for (i = 0; i < notes.length; i += 1) {
					editor.replace(notes[i], "").replace("<sup>nota</sup>", notes[i]);
				}
			}
		}
	});
	pathoschild.TemplateScript.add({
		name: 'cioe to cioè',
		forNamespaces: [108],
		renderer: 'buttonbox',
		script: function(editor){
			editor.replace('cioe','cioè');
		}
	});
});