Մասնակից:ԱշոտՏՆՂ/Gadget-editFormAutore.js

Վիքիդարանից՝ ազատ գրադարանից

Ծանուցում. Հիշելուց հետո կատարված փոփոխությունները տեսնելու համար մաքրեք ձեր զննարկիչի հիշապահեստը. Mozilla / Firefox / Safari՝ Ctrl+Shift+R (Cmd+Shift+R Mac OS X-ում) Konqueror՝ F5 Opera՝ Tools→Preferences ընտրացանկից։ Internet Explorer՝ Ctrl+F5

/* 
 * Custom edit form for author pages (namespace Autore).
 *
 * Based on
 * https://it.wikisource.org/wiki/MediaWiki:Gadget-editFormAutore.js
 *
 * 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).",
				"Secolo di attività||Indicare il secolo in cui l'autore ha operato, scegliendolo dal menù. Se ha operato in più secoli cliccare su Aggiungi per aggiungere un altro campo.|D|M",
				"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.");

				// parameters with multiple values, to use in drop-down lists
				var campiAutorD = [];
				campiAutorD['Secolo di attività'] = new Array("", "XXI secolo", 
				"XX secolo", "XIX secolo", "XVIII secolo", "XVII secolo", "XVI secolo", 
				"XV secolo", "XIV secolo", "XIII secolo", "XII secolo", "XI secolo", 
				"X secolo", "IX secolo", "VIII secolo", "VII secolo", "VI secolo", 
				"V secolo", "IV secolo", "III secolo", "II secolo", "I secolo", 
				"I secolo a.C.", "II secolo a.C.", "III secolo a.C.", "IV secolo a.C.", "V secolo a.C.", 
				"VI secolo a.C.", "VII secolo a.C.", "VIII secolo a.C.", "Antichità"
				);


				/*
				 * 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à'
						 || param_name == 'Giorno e mese di nascita' || param_name == 'Giorno e mese di morte' ) {
							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="javascript:void(0)" id="closeEditFormButton">Torna al testo wiki</a></div><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 drop-down list
							if (size == "D") {
								str += '<select name="' + param_name + '">';

								for (j = 0; j < campiAutorD[param_name].length; j++) {
									str += '<option value="' + campiAutorD[param_name][j] + '"';
									if (value[k].toLowerCase() == campiAutorD[param_name][j].toLowerCase() ) str += ' selected';
									str += '>' + campiAutorD[param_name][j] + '</option>';
								}

								str += '</select>'; 
							}
							// show as a radiobutton
							else if (size == "R") {
								str += '<input type="radio" name="' + param_name + '" id="' + param_name + '_1" value="sì"';
								if (value[k] == "sì") str += ' checked';
								str +='/><label for="' + param_name + '_1">Sì</label><input type="radio" name="' + param_name + '_0" value="no"';
								if (value[k] == "no") str += ' checked';
								str += '/><label for="' + param_name + '_0">No</label>'; 
							}
							// show as a simple text field
							else 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="javascript:void(0)" class="addFieldButton" data-param="' + param_name + '">Aggiungi</a>';
						}

						str += '</td></tr>';
					}
				 
					str += '</table>';
					console.log('aggancio il form con wikiEditor ' + $('.wikiEditor-ui').length);
					$('.wikiEditor-ui').after('<div id="editFormAutoreContainer"><div id="editFormAutoreLeft" style="float:left;width:50%"></div>' 
						+ '<div style="float:right;width:50%"><div id="editFormAutoreRight" style="margin-left:10px"></div></div></div>');
					$('#editFormAutoreLeft').append($('.wikiEditor-ui'));
					$('#editFormAutoreRight').append(str);
					$('#closeEditFormButton').click(function() {
						closeEditForm();
					});

				 	//Creates a new field with name param_name, for multiple-values parameter.
					$('.addFieldButton').click(function() {
						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();
					impostaBottoni(verificaAutore);
					$('#editFormAutoreRight').parent().remove();
					$('.wikiEditor-ui').insertBefore($('#editFormAutoreContainer'));
					$('#editFormAutoreContainer').remove();
					$('.wikiEditor-ui').before('<div id="openEditFormButton" style="text-align:right"><a href="javascript:void(0)" id="startEditAutoreButton">Apri interfaccia avanzata</a></div>');
					$('#startEditAutoreButton').click(function() {
						startEditAutor();
					});
				};

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