MediaWiki:Gadget-InfoTemplates.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.
$(document).ready(function() {
	
	if (mw.config.get('wgCanonicalNamespace') == 'Index' || mw.config.get('wgCanonicalNamespace') == 'MediaWiki')
		return;
	if (mw.config.get('wgAction') != 'edit' && mw.config.get('wgAction') != 'submit')
		return;
	
	var recentTemplates = localStorage.getItem('recentTemplates');
	recentTemplates = (recentTemplates == null || recentTemplates == '') ? [] : recentTemplates.split(',');
	var currentTemplates = [];
	var currentModules = [];
	// exclude the most common magic words
	var magicWords = [ 'FULLPAGENAME', 'PAGENAME', 'BASEPAGENAME', 'ROOTPAGENAME', 'SUBPAGENAME', 'NAMESPACE'];
	
	// template già presenti nella toolbar, o troppo comuni perché serva ricordarseli
	var toolbarTemplates = [ 'Sc', 'Pt', 'RigaIntestazione', 'Centrato', 'A destra', 'Ac', 'AutoreCitato', 'Tc', 'TestoCitato', 'Ct', '§',
		'Intestazione', 'IncludiIntestazione', 'Qualità', 'Autore', 'Conteggio pagine' ];
	// template senza argomenti
	var noArgsTemplates = [ 'Nop', 'Colonna', 'AltraColonna', 'FineColonna', 'FineColonne' ];
	
	function showDoc(ns, pageName) {
		$.ajax({
			url: "/w/index.php?&title=" + ns + ":" + pageName
		}).fail(function(jqXHR, textStatus, errorThrown) {
			alert('Documentazione del template non trovata');
		}).done(function(response) {
			$('.info-templates-box').remove();
			content = $('#documentazione-content', response);
			if (ns == 'Modulo') {
				content = $('.mw-parser-output', response);
			}
			content.find('#documentazione-title, #template_doc_page_transcluded, .ambox, .mw-editsection, #toc, .metadata').remove();
			$('#mw-content-text').prepend('<div class="box info-templates-box">'
				+ '<div class="box-title">Documentazione del <a href="/wiki/' + ns + ':' + pageName + '" target="_blank">' 
					+ ns + ' ' + pageName + '</a>'
				+ '<span class="icon-close"></span></div>'
				+ '<div class="box-main info-templates-box-main"></div></div>');
			$('.info-templates-box-main').html(content.html());
			
			// se all'inizio della doc c'è un <p> con dentro solo un <br>, rimuovilo
			emptyInitialP = $('.info-templates-box-main p:first-child');
			if (emptyInitialP.html() != undefined && emptyInitialP.html().trim() == '<br>') {
				emptyInitialP.remove();
			}
			
			if ($('.info-templates-box-main').is(':empty'))
				$('.info-templates-box-main').html('<i>Documentazione non presente</i>');
			$('.info-templates-box').draggable({
			    create: function( event, ui ) {
			        $(this).css({
			            right: "auto",
			            top: $(this).position().top,
			            left: $(this).position().left
			        });
			    }
			});
			$('.info-templates-box').draggable('option', 'cancel', '.info-templates-box-main');
			$('.info-templates-box .icon-close').click(function() {
				$('.info-templates-box').remove();
			});
		});
	}
	
	function saveRecentTemplates() {
		// tieni solo gli ultimi 10 template usati
		if (recentTemplates.length > 10) {
			recentTemplates.splice(0, recentTemplates.length - 10);
		}
		localStorage.setItem('recentTemplates', recentTemplates);
	}
	
	function findTemplates() {
		templates = [];
		text = $('#wpTextbox1').val();
		if (mw.config.get('wgCanonicalNamespace') == 'Page') {
			text += $('#wpHeaderTextbox').val() + $('#wpFooterTextbox').val();
		}
		tplList = text.match(/\{\{([^#]*?)[\|\}]/g);
		if (tplList) {
			for (i = 0; i < tplList.length; i++) {
				tpl = tplList[i].replace(/[\n\{\}\|\\]/g, '').replace(/_/g, ' ');
				if (tpl.indexOf("\"") != -1) {
					tpl.substring(0, tpl.indexOf("\""));
				}
				if (tpl.indexOf("\'") != -1) {
					tpl.substring(0, tpl.indexOf("\'"));
				}
				if (tpl.length > 0) {
					tpl = tpl.charAt(0).toUpperCase() + tpl.slice(1);
					if (tpl.length < 50 && !templates.includes(tpl) && !magicWords.includes(tpl) && tpl.indexOf(":") == -1 && (isNaN(tpl) || tpl.length > 2) ) {
						templates.push(tpl.trim());
					}
				}
			}
			templates.sort();
		}
		//console.log(templates);
			
		if (templates.join('|') != currentTemplates.join('|')) {
			currentTemplates = templates;
			
			$('#info-templates-list').empty();
			if (templates.length > 0) {
				$('#info-templates-list').append('&nbsp;<span class="info-templates-label">Info template usati: </span>');
				for (i = 0; i < templates.length; i++) {
					tmpl = templates[i];
					$('#info-templates-list').append('<div class="btn blue">' + tmpl + '</div>');
					if (!toolbarTemplates.includes(tmpl) && !recentTemplates.includes(tmpl)) {
						
						// check if template exists
						$.ajax({
							url: "/w/index.php?&title=Template:" + tmpl,
							templateName: tmpl
						}).done(function(response) {
							recentTemplates.push(this.templateName);
							
							saveRecentTemplates();
						});
					}
				}
				$('#info-templates-list .btn').click(function(e) {
					showDoc('Template', $(this).text());
				});
			}
		}
		
		if (recentTemplates.length > 0) {
			$('#recent-templates').empty();
			$('#recent-templates').append('&nbsp;<span class="recent-templates-label">Inserisci template recente: </span>');
			
			sortedRecentTemplates = recentTemplates.slice().sort(function (a, b) {
				return a.toLowerCase().localeCompare(b.toLowerCase());
			});
			for (i = 0; i < sortedRecentTemplates.length; i++) {
				$('#recent-templates').append('<a href="#" class="insert-recent-template">' + sortedRecentTemplates[i] + '</a> ');
			}
			$('.insert-recent-template').click(function(e) {
				e.preventDefault();
				var templ = $(this).html();
				var selezione = selection();
				
				var hasArgs = true;
				for (var i = 0; i < noArgsTemplates.length; i++) {
					if (templ.toLowerCase() == noArgsTemplates[i].toLowerCase()) {
						hasArgs = false;
						break;
					}
				}
				
				var beforeCursor = selezione[0] + "{" + "{" + templ + (hasArgs ? '|' : '') + selezione[1];
				scriviBox(beforeCursor + "}}" + selezione[2]);
				$('#wpTextbox1').prop('selectionStart', beforeCursor.length);
				$('#wpTextbox1').prop('selectionEnd', beforeCursor.length);
				$('#wpTextbox1').focus();
				
				// rimuovi e riaggiungilo in fondo
				var index = recentTemplates.indexOf(templ);
				if (index > -1) {
					recentTemplates.splice(index, 1);
					recentTemplates.push(templ);
				}
				saveRecentTemplates();
			});
		}
		
		modules = [];
		text = $('#wpTextbox1').val();
		list = text.match(/\{\{\s*#invoke:\s*(.*?)\s*\|/g);
		if (list) {
			for (i = 0; i < list.length; i++) {
				tpl = list[i].replace(/\{\{\s*#invoke:\s*/g, '').replace(/\s*\|/, '');
				tpl = tpl.charAt(0).toUpperCase() + tpl.slice(1);
				if (tpl.length < 50 && !modules.includes(tpl))
					modules.push(tpl);
			}
			modules.sort();
		}
		
		if (modules.join('|') != currentModules.join('|')) {
			currentModules = modules;
			
			$('#info-modules-list').empty();
			if (modules.length > 0) {
				$('#info-modules-list').append('<span class="info-templates-label">Moduli usati: </span>');
				for (i = 0; i < modules.length; i++) {
					$('#info-modules-list').append('<div class="btn blue">' + modules[i] + '</div>');
				}
				$('#info-modules-list .btn').click(function(e) {
					showDoc('Modulo', $(this).text());
				});
			}
		}
	}
	
	/*if (mw.config.get('wgCanonicalNamespace') == 'Page') {
		$('.prp-page-content').prepend('<div id="info-templates-list"></div>');
	} else {*/
		$('#wikiEditor-ui-toolbar .tabs').after('<div id="info-templates-list"></div><div id="info-modules-list"></div><div id="recent-templates"></div>');
	//}
	
	findTemplates();
	
	setInterval(findTemplates, 1000);
});