MediaWiki:Gadget-editFormAutore.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.
/* 
 * Custom edit form for author pages (namespace Autore).
 *
 * Modulo di modifica avanzato per le pagine degli autori, adattato da vec.source
 *
 * based on proofread_index.js written by ThomasV
 * http://wikisource.org/w/extensions/ProofreadPage/proofread_index.js
 */
 
//carica EditFormAutor
if (mw.config.get("wgNamespaceNumber") == 102 && mw.config.get("wgTitle").indexOf("/")===-1) {
	//solo se stiamo modificando l'intera pagina
	if ($('[name=wpSection]').val() === '') {
		$(document).ready(function() {
			$.when(
				mw.loader.using( 'ext.wikiEditor' ), $.ready
			).then(function () {

				// the parameters of Template:Autore, in the form: "name|label|tooltip|dimension or type|M" 
				// (2 = textarea of 2 rows, R = radio button, D = drop-down list, M = multiple values separated by / )
				var campiAutor = new Array("Nome||Indicare il nome dell'autore. Esempio: Alessandro.",
				"Cognome||Indicare il cognome dell'autore. Esempio: Manzoni. Nel caso di autori antichi o medievali spesso non esiste la distinzione tra nome e cognome, oppure il cognome è ignoto; in questi casi lasciare vuoto.",
				"Disambigua||In caso di omonimia con un altro autore (o altri autori), indicare tra parentesi le parole utili per distinguere questo autore dall'altro (o dagli altri), generalmente (attività) oppure (attività + secolo). Esempio: (numismatico); (poeta del Seicento).",
				"Attività||Indicare l'attività dell'autore. Esempio: poeta. Se è necessario indicarne più di una, cliccare su Aggiungi per aggiungere un altro campo.||M",
				"Nazionalità||Indicare la nazionalità dell'autore. Esempio: italiano. Lasciare vuoto qualora l'autore non sia chiaramente riconducibile ad una nazionalità ben precisa.",
				"Professione e nazionalità|Descrizione (facoltativa)|Inserire una breve descrizione dell'autore. Se questo campo è vuoto, la descrizione verrà costruita a partire dall'attività e dalla nazionalità indicate. Esempio: poeta e scrittore italiano.");

				function setButtons(fun) {
					$(document).ready(function () {
						
						$('#wpSave').click(fun);
						
						if (mw.user.options.get('uselivepreview') != '1') {
							console.log("La Live Preview è disabilitata!");
							$('#wpPreview').click(fun);
							$('#wpDiff').click(fun);
						} else {
							console.log("La Live Preview è abilitata!");
						}
					});
				}

				/*
				 * Get the value of a template parameter
				 * str: the text of the template
				 * param_name: the name of the parameter
				 */
				findparamTemplate = function(str, param_name) {
					var pattern = "\\n([\\s]*?)\\|([\\s]*?)" + param_name + "([\\s]*?)=([\\s\\S]*?)\\n([\\s]*?)\\|([^=\\n\\|]+)=";
					var re = new RegExp(pattern);
					var m = str.match(re);
					if (m) {
						val = m[4];
				 
						//niente note tra i parametri
						nota = find_stringa(val, "<ref>", "</ref>", true, "");
						while (nota !== "") {
							val = val.replace(nota,"");
							nota = find_stringa(val, "<ref>", "</ref>", true, "");
						}
				 
						return val;
					}
					return '';
				};

				//controlla che dopo il }} che chiude il template non sia rimasta della robaccia in più
				togliRobaccia = function(testo) {
					testo2 = testo.substring(2) + "}}";
					var i = 1;
					var fine = 2;
				 
					while (i > 0) {
						var open = testo2.search("{{");
						var close = testo2.search("}}");
						if (open != -1 && open < close) { 
							i++;
							testo2 = testo2.substring(open + 2);
							fine += open + 2;
						}
						else { 
							i--;
							testo2 = testo2.substring(close + 2);
							fine += close + 2;
						}
					}
					return testo.substring(0, fine - 2);
				};


				/*
				 * Called before page submit.
				 * Takes field values and builds the text to be saved
				 */
				endEditAutor = function() {
				
					//do nothing if we are saving the page as redirect
					if ($('#wpTextbox1').length && $('#wpTextbox1').val().toLowerCase().indexOf('#rinvia') != -1) { return; }
					if ($('#wpTextbox1').length && $('#wpTextbox1').val().toLowerCase().indexOf('#redirect') != -1) { return; }
					if ($('#wpTextbox1').length && $('#wpTextbox1').val().toLowerCase().indexOf('{' + '{disambigua' + '}}') != -1) { return; }
				
					var form = document.getElementById("editform");
					var template = "{{Autore";
					var textdata = '<!-- Area dati: non modificare da qui: --><onlyinclude><div style="display:none">';
				 
					for (i = 0; i < campiAutor.length; i++) {
						m = campiAutor[i].split('|');
						var param_name = m[0];
						var param_type = m[3];
						var value = "";
				 
						if (!form.elements[param_name]) continue;
				 
						$('[name="' + param_name + '"]').each(function(i) {
							thisVal = $.trim($(this).val());
							if (thisVal !== '') {
								if (value !== '') value += '/';
								value += thisVal;
							}
						});
				 
						// remove trailing \n
						value = value.replace(/\n$/,'');
				
						//to lower case for some fields
						if (param_name == 'Attività' || param_name == 'Nazionalità') {
							value = value.toLowerCase();
						}
				
						// replace pipe symbol everywhere...
						value = value.replace(/\|/g,'{{!}}');
				 
						// ...except in links...
						do { 
							prev = value;
							value = value.replace(/\[\[(.*?)\{\{!\}\}(.*?)\]\]/g,'[[$1|$2]]');
						}
						while (value != prev);
				 
						// ..and in templates
						do { 
							prev = value;
							value = value.replace(/\{\{(.*?)\{\{!\}\}(.*?)\}\}/g,'{' + '{$1|$2}}');
						}
						while (value != prev);
				 
						//scriviamo sempre i parametri, anche se sono vuoti, per compatibilità
						//tranne il disambigua che non serve quasi mai
						if ( (param_name != "Disambigua" && param_name != "Attività" && param_name != "Nazionalità")
							|| value !== "") {
							template = template + '\n| ' + param_name + ' = ' + value;
						}
				
						if (value !== "") {
							textdata = textdata + '<section begin="' + param_name + '"/>' 
								+ value.replace(/<ref>(.*?)<\/ref>/g, "") + '<section end="' + param_name + '"/>\n';
						}
					}

					template = template + "\n}}\n";
					textdata = textdata + "</div></onlyinclude><!-- a qui -->";

					//re-assemble the complete wikitext
					form.elements.wpTextbox1.value = textdata + template + form.elements.wpTextbox1.value;
				};

				/*
				 * Called on load.
				 * Builds the edit form.
				 */
				startEditAutor = function() {
					console.log('startEditAutor');

					//esci se il namespace non è Autore
					if (mw.config.get("wgNamespaceNumber") != 102) { return; }

					$('#openEditFormButton').remove();
				
					var text = document.getElementById("wpTextbox1"); 
					if (!text) { return; }
					var testo = text.value;
					console.log('testo: ' + testo);
					
					var reDis = /\{\{[Dd]isambigua\}\}/;
					if (testo.match(reDis)) { return; }

					// exit if the page does not contain Template:Autore
					params = '';
					if (testo) {
						var re = /\{\{[Aa]utore([\s\S]*)\n\}\}/m;
						var mm = testo.match(re);
						if (!mm) return; 
						params = togliRobaccia(mm[1]) + '\n\|END='; 
					}

					// take the text after Template:Autore
					// this should work also when Autore contains other templates
					begin = testo.search(/\{\{[Aa]utore/);
					testo = testo.substring(begin+2);
					var i = 1;
					while (i > 0) {
						var open = testo.search("{{");
						var close = testo.search("}}");
						if (open != -1 && open < close) { 
							i++;
							testo = testo.substring(open+2);
						}
						else { 
							i--;
							testo = testo.substring(close+2);
						}
					}
					
					//the remaining text (trimming initial newlines)
					$('#wpTextbox1').val(testo.replace(/^\s*/, ''));

					console.log('inizio a costruire il form...');

					// the html of the form
					var str = '<div style="text-align:right"><a href="#" id="closeEditFormButton" class="blue">Torna al testo wiki</a></div>';
					str += '<div style="text-align: center; padding: 10px; white-space: normal;"><b>Nota</b>: la sequenza dei campi Nome, Cognome e Disambigua <b>deve corrispondere al nome della pagina</b>.</div>';
					str += '<table width="100%">';

					//loop on every field
					for (i = 0; i < campiAutor.length; i++) {
						var m = campiAutor[i].split('|');
						param_name = m[0];

						// use the label if there is one
						if (m[1] && m[1] !== '') param_label = m[1]; 
						else param_label = param_name;

						//tooltip
						str += '<tr><td><span style="cursor:help;border-bottom:1px dotted;" title="' + m[2] + '">';
						str += param_label.replace(/\s/g, "&nbsp;") + ': </span></td>';

						// default size 1
						if (m[3]) size = m[3]; 
						else size="1";

						multiple = false;
						if (m[4] && m[4] == 'M') multiple = true;

						// get the value(s)
						allValues = findparamTemplate(params, param_name);
						allValues = $.trim(allValues.replace(/\{\{!\}\}/g,'|'));

						value = new Array(allValues);

						// in case of multiple values separated by /
						if (multiple) value = allValues.split("/");
						str += '<td width="50%"' + (multiple?'':' colspan="2"') + '>';
				 
						for (k = 0; k < value.length; k++) {
							// show as a simple text field
							if (size == "1") {
								str += '<input name="' + param_name + '" value="' + value[k] + '"/>'; 
							}
							// show as a textarea
							else {
								str += '<textarea name="' + param_name + '" rows='+size+'>' + value[k] + '</textarea>';
							}
						}

						if (multiple) {
							str += '</td><td style="vertical-align: bottom"><a href="#" class="addFieldButton blue" data-param="' + param_name + '">Aggiungi</a>';
						}

						str += '</td></tr>';
					}
				 
					if ($('#t-wikibase').length) {
						str += '<tr><td colspan="2" style="text-align: center"><br>Per modificare gli altri dati dell\'autore, visita l\'<b>' + $('#t-wikibase').html() + '</b>.<br><br></td></tr>';
					}
					
					str += '</table>';
					console.log('aggancio il form con wikiEditor ' + $('.wikiEditor-ui').length);
					$('.wikiEditor-ui').after('<div id="editFormAutoreContainer"><div id="editFormAutoreLeft"></div>' 
						+ '<div id="editFormAutoreRightBox"><div id="editFormAutoreRight"></div></div></div>');
					$('#editFormAutoreLeft').append($('.wikiEditor-ui'));
					$('#editFormAutoreRight').append(str);
					
					$('#editFormAutoreLeft').css('display', 'inline-block');
					$('#editFormAutoreLeft').css('width', '50%');
					$('#editFormAutoreLeft').css('vertical-align', 'top');
					$('#editFormAutoreRightBox').css('display', 'inline-block');
					$('#editFormAutoreRightBox').css('width', '50%');
					$('#editFormAutoreRightBox').css('vertical-align', 'top');
					$('#editFormAutoreRight').css('margin-left', '10px');
					$('#editFormAutoreContainer').css('background-color', '#eaecf0');
					$('#editFormAutoreContainer').css('border-right', '1px solid #c8ccd1');
					
					$('#closeEditFormButton').click(function(e) {
						e.preventDefault();
						closeEditForm();
					});

				 	//Creates a new field with name param_name, for multiple-values parameter.
					$('.addFieldButton').click(function(e) {
						e.preventDefault();
						param_name = $(this).data('param');
						$lastField = $('[name="' + param_name + '"]:last');
						$lastField.after($lastField.clone().val(''));
					});
				};

				//close edit form and show the standard wiki text
				closeEditForm = function() {
					endEditAutor();
					elabNs0();
					setButtons(verificaAutore);
					$('#editFormAutoreRight').parent().remove();
					$('.wikiEditor-ui').insertBefore($('#editFormAutoreContainer'));
					$('#editFormAutoreContainer').remove();
					$('.wikiEditor-ui').before('<div id="openEditFormButton" style="text-align:right"><a href="#" id="startEditAutoreButton" class="blue">Apri interfaccia avanzata</a></div>');
					$('#startEditAutoreButton').click(function(e) {
						e.preventDefault();
						startEditAutor();
					});
				};

				console.log('inizio a costruire il tutto');
				startEditAutor();
				
				// change the 3 buttons so that they call endEditAutor() before submit
				setButtons(endEditAutor);
			});
		});
	}
}