MediaWiki:Gadget-EditFormNs0.js

Da Wikisource

Ocio: Daspò ver salvà, podaria esare neçesario snetare ła cache dal propio navegadore web par vedare i canbiamenti.

  • Firefox / Safari: tegner strucà el boton de łe letare grande Shift e schiciare sora Ricarga, o se nò struca Ctrl-F5 o Ctrl-R (⌘-R so Mac)
  • Google Chrome: strucare Ctrl-Shift-R (⌘-Shift-R so on Mac)
  • Internet Explorer / Edge: tegner strucà el boton Ctrl e schiciare so Ajorna, o sinò Ctrl-F5
  • Opera: Va in tel Menu → Inpostasion (Opera → Prefarense so on Mac) e pò in Privacy & sicuresa → Sneta dati del navegadore → Imajini e file in te ła cache.
/* 
 * Custom edit form for namespace-0 pages.
 * Pages must contain, in this order: 
 * 1) Template:ContegioPagine (template for counting pages)
 * 2) Template:Intestazion (template header)
 * 3) text of the page
 *
 * Modulo de modifica par le pagine del namespace prinsipale, adatà par vec.source
 *
 * based on proofread_index.js written by ThomasV
 * http://wikisource.org/w/extensions/ProofreadPage/proofread_index.js
 */

$(document).ready(function() {
	$.when(mw.loader.using('ext.wikiEditor'), $.ready).then(function() {
		var api = new mw.Api();
		var regexPageCount = /{{ContegioPagine\|\[\[Speciale:Statìsteghe\]\]}}[\r\n]*/gi;
		
		// the parameters of Template:Intestazion, in the form: "name|label|dimension or type" 
		// (2 = textarea of 2 rows, R = radio button, D = drop-down list)
		var campi = new Array('qualità|Qualità del testo (<a target="_new" href=\"\/wiki\/Ajuto:Qualità_dei_testi\">ajuto</a>)|D', "titolo|Titolo de l'opera|2", "sezion|Titolo de la sotopagina", "racolta|Racolta", "sudivision|Sudivision interna<br/><small>(es. Parte I, Libro Secondo ecc.)</small>", 
		"prima|Testo presedente|2", "dopo|Testo sucessivo|2", "autor|Autor", "sorascrivi autor|Mostra l\'autor come<br/><small>(solo par soranomi e pseudonimi)</small>", 
		"traduzion|Tradussion de", "musica de|Musicà da", "ano|Ano de publicassion", "secolo|Secolo|D", "tipologia|Tipologia de testo|D", "dialeto|Dialeto|D", "indice|Indice <a href=\"\/wiki\/Ajuto:Proofread\">proofread</a>", "edission|Edission originale<br/><small>(compila solo in mancansa de un Indice)</small>|2", "fonte|<a href=\"\/wiki\/Ajuto:Fonte\">Fonte</a> del testo<br/><small>(compila solo in mancansa de un Indice)</small>|2", "wikipedia|Voce su Wikipedia", "note|Note|2");
		
		// parameters with multiple values, to use in drop-down lists
		var campiD = [];
		campiD['qualità'] = new Array("1|Testo inconpleto", "2|Testo da sistemar", "3|Testo conpleto", "4|Testo rileto");
		campiD.secolo = new Array("", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX", "XXI");
		campiD.tipologia = new Array("", "Apologhi", "Cansoni popolari", "Canzonete", "Comedie", "Ditirambi", 
		"Documenti storici", "Epigrami", "Filastroche", "Madrigali", "Mariegole", "Novele", "Poemi", 
		"Poesie", "Preghiere", "Racolte de poesie", "Soneti", "Testi in prosa", "Testi teatrali", "Vilote");
		campiD.dialeto = new Array("", "bisiac", "graisan", "triestin", "veronese", "visentin");
		
		
		setQualityIcon = function() {
			var qualita = $('[name=qualità]');
			qualita.next().remove();
			
			if (qualita.val() == 1) {
				qualita.after('<img src="//upload.wikimedia.org/wikipedia/commons/thumb/3/34/25%25.svg/18px-25%25.svg.png"/>');
			} else if (qualita.val() == 2) {
				qualita.after('<img src="//upload.wikimedia.org/wikipedia/commons/thumb/c/c2/50%25.svg/18px-50%25.svg.png"/>');
			} else if (qualita.val() == 3) {
				qualita.after('<img src="//upload.wikimedia.org/wikipedia/commons/thumb/4/49/75%25.svg/18px-75%25.svg.png"/>');
			} else if (qualita.val() == 4) {
				qualita.after('<img src="//upload.wikimedia.org/wikipedia/commons/thumb/2/24/100_percent.svg/18px-100_percent.svg.png"/>');
			}
		};
		
		/*
		 * Called on load.
		 * Builds the edit form.
		 */
		startEditNs0 = function(firstTime) {
		
			if (typeof firstTime == "undefined") { firstTime = true; }
		
			if (mw.config.get('wgNamespaceNumber') !== 0) { return false; }
		
			$('#openEditFormButton').remove();
		
			var text = document.getElementById("wpTextbox1"); 
			if (!text) { return false; }
			var testo = text.value;
		
			// exit if the page does not contain Template:Intestazion
			params = '';
			if (testo) {
				var re = /\{\{[Ii]ntestazion([\s\S]*)\n\}\}/m;
				m = testo.match(re);
				if (firstTime && !m) return false;
				params = m[1] + '\n\|END=';
			}
		
			// take the text after Template:Intestazion
			// this should work also when Intestazion contains other templates
			begin = testo.search(/\{\{[Ii]ntestazion/);
			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*/, ''));
		
			// if the current page title contains a slash "/", we consider it to be a sub-page
			var isSubPage = false;
			var rows = "44";
			if (mw.config.get('wgTitle').indexOf("/") != -1) {
				isSubPage = true;
				rows = "20";
			}
		
			// the html of the form
			var str = '<div id="editFormAutoreRightHeader"><a id="closeEditFormButton" href="javascript:void(0)">Torna al testo wiki</a></div><table width="100%">';
		
			//loop on every field
			for (i = 0; i < campi.length; i++) {
				m = campi[i].split('|');
				param_name = m[0];
		
				// do not show certain fields, depending if we are in a sub-page or not
				if (isSubPage) {
					//show "fonte" if title contains magic words like "Volume"
		
					if (param_name == "qualità" || param_name == "edission" || param_name == "fonte" || param_name == "ano" 
					|| param_name == "autor" || param_name == "sorascrivi autor" || param_name == "traduzion" || param_name == "musica de" 
					|| param_name == "secolo" || param_name == "tipologia" || param_name == "dialeto" || param_name == "wikipedia"
					|| (param_name == "indice" && mw.config.get('wgTitle').indexOf("Volume") == -1 && mw.config.get('wgTitle').indexOf("Tomo") == -1) ) continue;
				}
				else {
					if (param_name == "sezion") continue;
				}
		
				// use the label if there is one
				if (m[1]) param_label = m[1]; 
				else param_label = param_name;
		
				if (isSubPage && param_name == "titolo") { param_label += " (opzionale)" }
		
				str += '<tr><td>' + param_label + ': </td><td width="75%">';
		
				// default size 1
				if (m[2]) size = m[2]; 
				else size="1";
		
				// get the value
				value = findparam(params, param_name);
				value = value.replace(/\{\{!\}\}/g,'|');
		
				// show as a drop-down list
				if (size == "D") {
					str += '<select name="' + param_name + '">';
		
					for (j = 0; j < campiD[param_name].length; j++) {
						op = campiD[param_name][j].split('|');
						option_value = op[0];
						if (op[1]) option_label = op[1];
						else option_label = op[0];
		
						str += '<option value="' + option_value + '"';
						if (value.toLowerCase() == option_value.toLowerCase() ) str += ' selected';
						str += '>' + option_label + '</option>';
					}
		
					str += '</select>'; 
				}
				// show as a radiobutton
				else if (size == "R") {
					str += '<input type="radio" name="' + param_name + '" value="sì"';
					if (value == "sì") str += ' checked';
					str +='/>Sì&nbsp;&nbsp;<input type="radio" name="' + param_name + '" value="no"';
					if (value == "no") str += ' checked';
					str += '/>No'; 
				}
				// show as a simple text field
				else if (size == "1") {
					str += '<input name="' + param_name + '" value="'+value+'"/>'; 
				}
				// show as a textarea
				else {
					str += '<textarea name="' + param_name + '" rows='+size+'>'+value+'</textarea>';
				}
			}
		
			str += '</td></tr></table>';
			$('.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);
		
			//close edit form and show the standard wiki text
			$('#closeEditFormButton').click(function() {
				endEditNs0();
				$('#editFormAutoreRight').parent().remove();
				$('.wikiEditor-ui').insertBefore($('#editFormAutoreContainer'));
				$('#editFormAutoreContainer').remove();
				$('.wikiEditor-ui').before('<div id="openEditFormButton" style="text-align:right"><a href="javascript:void(0)" onclick="startEditNs0(false)">Torna in modalità avansada</a></div>');
			});
		
			// change the 3 buttons so that they call endEditNs0() before submit
			impostaBottoni(endEditNs0);
			
			setQualityIcon();
			$('select[name=qualità]').change(function() {
				setQualityIcon();
			});
			
			// on page creation
			if (mw.config.get("wgArticleId") == 0) {
				
				var title = mw.config.get("wgTitle");
				if (title.indexOf('/') != -1) {
					if ($('[name="sezion"').val() == '')
						$('[name="sezion"').val(title.substring(title.lastIndexOf('/') + 1));
				} else {
					if ($('[name="titolo"').val() == '')
						$('[name="titolo"').val(title);
				}
				
				// cerca l'indice che punta a questa pagina
				api.get({
					action: 'query', 
					format: 'json', 
					list: 'backlinks', 
					blnamespace: '104', 
					bltitle: mw.config.get("wgPageName")
				}).done(function(data) {
					backlinks = data.query.backlinks;
					if (backlinks != undefined && backlinks[0] != undefined) {
						indice = backlinks[0].title;
						console.info('EditFormNs0: gò catà un indice che ponta qua: ' + indice);
						
						if ($('#wpTextbox1').val() == '')
							$('#wpTextbox1').val('<pages index="' + indice.replace('Indice:', '') + '" from="" to="" fromsection="" tosection="" />');
							
						$.ajax({
							url: "/w/index.php?&title=" + indice
						}).done(function(data) {
							$('[name="autor"]').val($('#dati-autore', data).text());
							
							somario = $('#remarks', data);
							allLinks = somario.find('a');
							link = somario.find('a[title^="' + mw.config.get("wgTitle") + ' ("]');
							i = allLinks.index(link);

							if (i != -1) {
								next = $(allLinks.get(i + 1));
								if (next.attr('title') != undefined) {
									nextTitle = next.attr('title').replace(/ \([a-złàèéìòóù].*?\)/, '').replace(/’/g, "'");
									if ($('[name="dopo"]').val() == '')
										$('[name="dopo"]').val(nextTitle);
								}
							}
								
							if (i > 0) {
								prev = $(allLinks.get(i - 1));
								prevTitle = prev.attr('title').replace(/ \([a-złàèéìòóù].*?\)/, '').replace(/’/g, "'");
								if ($('[name="prima"]').val() == '')
									$('[name="prima"]').val(prevTitle);
								
								if (!prev.hasClass('new')) {
									console.info('Cargo la pagina ' + prevTitle);
									api.get({
										action: 'parse', 
										format: 'json', 
										prop: 'wikitext',
										page: prevTitle.replace(/ /, '_')
									}).done(function(data) {
										testo = data.parse.wikitext["*"];
										params = '';
										if (testo) {
											var re = /\{\{[Ii]ntestazion([\s\S]*)\n\}\}/m;
											m = testo.match(re);
											params = m[1] + '\n\|END='; 
										}
										
										$('#editFormAutoreRightHeader').prepend(' - ');
										$('#editFormAutoreRightHeader').prepend('<a id="copyInfoButton" href="javascript:void(0)">Copia da quel de prima</a>');
										$('#copyInfoButton').click(function() {
											copyParams = ['racolta', 'sudivision', 'ano', 'secolo', 'tipologia', 'dialeto'];
											for (i = 0; i < copyParams.length; i++) {
												$('[name="' + copyParams[i] + '"]').val(findparam(params, copyParams[i]));
											}
										});
									});
								}
							}
						});
					} else {
						// nissun indese ponta qua
						if ($('#wpTextbox1').val() == '') {
							var title = mw.config.get("wgTitle");
							if (title.indexOf('/') != -1) {
								title = title.substring(0, title.indexOf('/'));
								console.info('Cargo la pagina base ' + title);
								
								$.ajax({
									url: "/w/index.php?&title=" + title
								}).done(function(data) {
									var indice = $('#indice', data);
									if (indice.length) {
										$('#wpTextbox1').val('<pages index="' + indice.text().replace('Indice:', '') + '" from="" to="" fromsection="" tosection="" />');
									}
									
									somario = $('.ws-summary', data);
									allLinks = somario.find('a');
									link = somario.find('a[title^="' + mw.config.get("wgTitle") + ' ("]');
									i = allLinks.index(link);
									if (i != -1) {
										prev = $(allLinks.get(i - 1));
										next = $(allLinks.get(i + 1));
										prevTitle = prev.attr('title').replace(/ \([a-z].*?\)/, '').replace(title, '..');
										if ($('[name="prima"]').val() == '')
											$('[name="prima"]').val(prevTitle);
											
										if (next.attr('title') != undefined) {
											nextTitle = next.attr('title').replace(/ \([a-z].*?\)/, '').replace(title, '..');
											if ($('[name="dopo"]').val() == '')
												$('[name="dopo"]').val(nextTitle);
										}
									}
								})
							}
						}
					}
				});
			}
		};
		
		/*
		 * Called before page submit.
		 * Takes field values and builds the text to be saved
		 */
		endEditNs0 = function() {
		
			//exit if we are not using the new form
			if ($("#formNovo").css('display') == 'none') return;
			
			if ($('#wpTextbox1').val().toUpperCase().indexOf('#RINVIA') != -1 || $('#wpTextbox1').val().toUpperCase().indexOf('#REDIRECT') != -1) return;
		
			var form = document.getElementById("editform");
			var template = "{{intestazion";
			var textdata = '<div id="areaDati" style="display:none">';
		
			//if the user didn't enter the Index page, let's look if we find it in the page text
			if (form.elements.indice && form.elements.indice.value === "") {
		
				var tag = "<pages index=\"";
				var indice = form.elements.wpTextbox1.value;
				var start = indice.search(tag);
				if (start != -1) {
					indice = indice.substring(start + tag.length);
					indice = indice.substring(0, indice.search("\""));
					form.elements.indice.value = "Indice:" + indice;
				}
			}
		
			for (i = 0; i < campi.length; i++) {
				m = campi[i].split('|');
				var param_name = m[0];
				var param_type = m[2];
				var value = "";
		
				if (!form.elements[param_name]) continue;
		
				if (param_type == "R") {
					value = getRadioValue(form.elements[param_name]);
				}
				else {
					value = form.elements[param_name].value;
				}
		
				// remove trailing \n
				value = value.replace(/\n$/,'');
		
				// 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);
		
				if (value !== "") {
					template = template + '\n|' + param_name + '=' + value;
					textdata = textdata + '\n<section begin="' + param_name + '"/>' + value.replace(/<ref>(.*?)<\/ref>/g, "") + '<section end="' + param_name + '"/>';
				}
			}
		
			template = template + "\n}}\n";
			textdata = textdata + "</div>";
		
			var result = textdata + "{{ContegioPagine|[[Speciale:Statìsteghe]]}}\n" + template;
		
			form.elements.wpTextbox1.value = result + form.elements.wpTextbox1.value;
		
			//resetta i botoni
			impostaBottoni(null);
		};
		
		startEditNs0();
	});
});
Traesto fora da Wikipèdia - L'ençiclopedia łìbara e cołaboradiva in łéngua Vèneta "https://vec.wikisource.org/w/index.php?title=MediaWiki:Gadget-EditFormNs0.js&oldid=73965"