Utente:Ferdi2005/common.js

Da Wikipedia, l'enciclopedia libera.
Vai alla navigazione Vai alla ricerca

Questa pagina definisce alcuni parametri di aspetto e comportamento generale di tutte le pagine. Per personalizzarli vedi Aiuto:Stile utente.


Nota: dopo aver salvato è necessario pulire la cache del proprio browser per vedere i cambiamenti (per le pagine globali è comunque necessario attendere qualche minuto). Per Mozilla / Firefox / Safari: fare clic su Ricarica tenendo premuto il tasto delle maiuscole, oppure premere Ctrl-F5 o Ctrl-R (Command-R su Mac); per Chrome: premere Ctrl-Shift-R (Command-Shift-R su un Mac); per Konqueror: premere il pulsante Ricarica o il tasto F5; per Opera può essere necessario svuotare completamente la cache dal menù Strumenti → Preferenze; per Internet Explorer: mantenere premuto il tasto Ctrl mentre si preme il pulsante Aggiorna o premere Ctrl-F5.

mw.loader.load( '//it.wikipedia.org/w/index.php?title=Utente:Ferdi2005/autoFormatter.js&action=raw&ctype=text/javascript' );

mw.loader.load( '//en.wikipedia.org/w/index.php?title=User:DannyS712/Undo.js&action=raw&ctype=text/javascript' );

// No log-out involontari
var $span = $( '<span>' ).on( 'click', function ( e ) { e.stopPropagation() } ); $( '#pt-logout a' ).wrapInner( $span );

// Web2Cit
mw.loader.load( '//en.wikipedia.org/w/index.php?title=User:Diegodlh/Web2Cit/script.js&action=raw&ctype=text/javascript' ); // Backlink: [[:en:User:Diegodlh/Web2Cit/script.js]]

 // Link alle sezioni
mw.loader.using( [ 'mediawiki.util', 'user' ], function () {
	'use strict';

	$( function ( $ ) {
		var lang = mw.config.get( 'wgUserLanguage' ),
			messages = {
				en: {
					'ancretitres-anchor-name': '[URL]',
					'ancretitres-internal-link-name': '[[Link]]',
					'ancretitres-description': 'Get an URL to this section',
					'ancretitres-int-description': 'Get an internal link to this section',
					'ancretitres-notif-title': 'Text copied to clipboard',
					'ancretitres-notif-error': 'Could not copy to clipboard'
				},
				fr: {
					'ancretitres-anchor-name': '[URL]',
					'ancretitres-internal-link-name': '[[Lien]]',
					'ancretitres-description': 'Obtenir une URL vers cette section',
					'ancretitres-int-description': 'Obtenir un lien interne vers cette section',
					'ancretitres-notif-title': 'Texte copié dans le presse-papiers',
					'ancretitres-notif-error': 'Impossible de copier dans le presse-papiers'
				}
			},
			options = {
				afficheE: true,
				afficheI: true
			};

		mw.messages.set( messages.en );
		if ( lang !== 'en' && lang in messages ) {
			mw.messages.set( messages[ lang ] );
		}

		// https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript/30810322#30810322
		function copyTextToClipboard( text ) {
			var textArea = document.createElement( 'textarea' );

			textArea.style.position = 'fixed';
			textArea.style.top = 0;
			textArea.style.left = 0;

			textArea.style.width = '2em';
			textArea.style.height = '2em';
			textArea.style.padding = 0;
			textArea.style.border = 'none';
			textArea.style.outline = 'none';
			textArea.style.boxShadow = 'none';
			textArea.style.background = 'transparent';

			textArea.value = text;

			document.body.appendChild( textArea );
			textArea.focus();
			textArea.select();

			var copySuccess;
			try {
				document.execCommand( 'copy' );
				copySuccess = true;
			} catch ( e ) {
				copySuccess = false;
			}

			document.body.removeChild( textArea );

			if ( copySuccess ) {
				mw.notify( text, { title: mw.msg( 'ancretitres-notif-title' ), tag: 'ancretitres', type: 'info', autoHide: true } );
			} else {
				mw.notify( mw.msg( 'ancretitres-notif-error' ), { tag: 'ancretitres', type: 'error', autoHide: true } );
			}
		}

		if ( typeof window.AncreTitres !== 'undefined' ) {
			$.extend( options, window.AncreTitres );
		}

		if ( !options.afficheI && !options.afficheE ) {
			return;
		}

		$( 'span.mw-headline' ).each( function ( _, headline ) {
			var $span = $( '<span>' )
				.addClass( 'noprint ancretitres' )
				.css( {
					'font-size': 'xx-small',
					'font-weight': 'normal',
					'user-select': 'none' // jQuery se charge d'ajouter un vendor prefix si nécessaire
				} );

			if ( options.afficheE ) {
				var $linkE = $( '<a href="#" title="' + mw.msg( 'ancretitres-description' ) + '">' + mw.msg( 'ancretitres-anchor-name' ) + '</a>' ).click( function ( e ) {
					e.preventDefault();
					var outputText = 'https:' + mw.config.get( 'wgServer' ) + mw.util.getUrl() + '#' + headline.id;
					copyTextToClipboard( outputText );
				} );
				$span.append( ' ', $linkE );
			}

			if ( options.afficheI ) {
				var $linkI = $( '<a href="#" title="' + mw.msg( 'ancretitres-int-description' ) + '">' + mw.msg( 'ancretitres-internal-link-name' ) + '</a>' ).click( function ( e ) {
					e.preventDefault();
					var escapedAnchor = headline.id
						// escaping caractères spéciaux HTML
						// (partiel, '"& ne sont pas escapés pour ne pas dégrader inutilement la lisibilité du lien)
						.replace( /</g, '&lt;' )
						.replace( />/g, '&gt;' )
						// escaping caractères spéciaux MediaWiki
						.replace( /\[/g, '&#91;' )
						.replace( /\]/g, '&#93;' )
						.replace( /\{/g, '&#123;' )
						.replace( /\|/g, '&#124;' )
						.replace( /\}/g, '&#125;' );
					var outputText = '[[' + ( mw.config.get( 'wgPageName' ) + '#' + escapedAnchor ).replace( /_/g, ' ' ) + ']]';
					copyTextToClipboard( outputText );
				} );
				$span.append( ' ', $linkI );
			}

			$( headline ).parent().append( $span );
		} );

	} );

} );

/** 
 * Considera il testo selezionato come il titolo di una voce straniera, e lo
 * trasforma nel titolo dell'equivalente voce italiana
 */

/* global mediaWiki, jQuery, OO */
( function( mw, $ ) {
	'use strict';
	
	var cookieName = 'tradLinkLangs';
	var windowManager, optDialog;

	/** 
	 * Basato su [[Special:Permalink/109422525]] e gli esempi su mw.org
	 */
	function showDialog() {
		if ( optDialog ) {
			windowManager.openWindow( optDialog );
			return;
		}

		mw.util.addCSS(
			'.tradlinks-buttons { width: 100%; text-align: center; margin-top: 10px }' +
			'.tradlinks-error { color: red; font-size: 120%; font-weight: bold; text-align:center }'
		);
		function OptDialog( config ) {
			OptDialog.parent.call( this, config );
		}
		// TODO Valutare se sia possibile usare un ProcessDialog
		OO.inheritClass( OptDialog, OO.ui.Dialog );
		OptDialog.static.name = 'optDialog';
		// XXX Questo non viene visualizzato nei Dialog di base
		OptDialog.static.title = 'Configurazione del tool TradLink';
		OptDialog.prototype.initialize = function () {
			var self = this;
			OptDialog.parent.prototype.initialize.call( this );

			this.errorContainer = new OO.ui.LabelWidget( {
				label: ''
			} );
			this.addError = function ( error ) {
				self.errorContainer.setLabel(
					new OO.ui.HtmlSnippet( '<span class="tradlinks-error">' + error + '</span>' )
				);
			};
			this.clearError = function () {
				self.errorContainer.setLabel( '' );
			};

			this.fields = [];
			var lingue = getLingue();
			var count = 1;
			lingue.forEach( function( val ) {
				var input = new OO.ui.TextInputWidget( { 
					value: val || '',
					maxLength: 3
				} );
				input.on( 'change', self.clearError );
				var field = new OO.ui.FieldLayout(
					input,
					{
						label: 'Alt+' + count + ':',
						align: 'left'
					}
				);
				self.fields.push( field );
				count++;
			} );
			
			var fieldsetLayout = new OO.ui.FieldsetLayout( {
				items: this.fields,
				label: 'Elenco delle lingue da utilizzare per il tool TradLink'
			} );

			var submitButton = new OO.ui.ButtonWidget(
				{ label: 'Imposta' }
			).on( 'click', function () { submitDialogHandler( self.fields ); } );
			var cancelButton = new OO.ui.ButtonWidget(
				{ label: 'Annulla' }
			).on( 'click', function () { optDialog.close(); } );

			var buttonsLayout = new OO.ui.HorizontalLayout( {
				items: [ submitButton, cancelButton ],
				classes: [ 'tradlinks-buttons' ]
			} );

			this.panelLayout = new OO.ui.PanelLayout( { padded: true, expanded: false } );
			this.panelLayout.$element.append( fieldsetLayout.$element, buttonsLayout.$element, this.errorContainer.$element );
			this.$body.append( this.panelLayout.$element );
		};
		OptDialog.prototype.getBodyHeight = function () {
			return this.panelLayout.$element.outerHeight( true );
		};
		optDialog = new OptDialog( {
			size: 'small'
		} );
		windowManager = new OO.ui.WindowManager();
		$( 'body' ).append( windowManager.$element );
		windowManager.addWindows( [ optDialog, new OO.ui.MessageDialog() ] );
		windowManager.openWindow( optDialog );
	}

	/**
	 * Valida l'aggiunta di nuove lingue
	 * @param {array} formFields
	 */
	function submitDialogHandler( formFields ) {
		new mw.Api().get( {
			action: "sitematrix",
			smtype: "language",
			smlangprop: "code|site",
			smsiteprop: "url",
			smlimit: 5000,
			format: "json"
		} ).done( function ( data ) {
			var lingue = formFields.map( function( f ) {
				return f.fieldWidget.getValue().trim();
			} );

			var filteredMatrix = {};
			for ( var i in data.sitematrix ) {
				var siteData = data.sitematrix[i];
				if ( lingue.indexOf( siteData.code ) > -1 ) {
					filteredMatrix[siteData.code] = siteData.site;
				}
			}
					
			for ( var j in lingue ) {
				var code = lingue[j];
				if ( code === 'it' ) {
					optDialog.addError( 'Il codice "it" non può essere usato' );
					return;
				}
				if ( !( code in filteredMatrix ) ) {
					optDialog.addError( 'Codice lingua non riconosciuto: ' + code );
					return;
				}
				var found = false;
				for ( var s in filteredMatrix[code] ) {
					if ( filteredMatrix[code][s].url.indexOf( '.wikipedia.org' ) > -1 ) {
						found = true;
						break;
					}
				}
				if ( !found ) {
					optDialog.addError( 'Non esiste una Wikipedia nella seguente lingua: ' + code );
					return;
				}
			}

			mw.cookie.set( cookieName, lingue.join(), 20 * 365 * 24 * 60 * 60 * 1000 );
			optDialog.close();
		} ).fail( function ( e ) {
			console.error( 'Impossibile ottenere sitematrix: ' + e );
		} );
	}

	/**
	 * @return {array} Di codici lingua
	 */
	function getLingue() {
		var value = mw.cookie.get( cookieName );
		return value !== null
			? value.split( ',' ).slice( 0, 9 )
			: [ 'en', 'nl', 'de', 'sv', 'fr', 'ru', 'es', 'war', 'vi' ];
	}

	/**
	 * Routine principale
	 * @param {int} cod Indice della lingua (0-based)
	 */
	function tradLink( cod ) {
		var lingue = getLingue();

		new mw.ForeignApi( '//' + lingue[cod] + '.wikipedia.org/w/api.php' ).get( {
			action: "query",
			prop: "langlinks",
			lllang: "it",
			titles: $( '#wpTextbox1' ).textSelection( 'getSelection' ),
			format: "json",
			redirects: ""
		} ).done( function( data ) {
			var selStart = document.getElementById( 'wpTextbox1' ).selectionStart,
				selEnd = document.getElementById( 'wpTextbox1' ).selectionEnd;
			if (
				typeof( data.query ) != "undefined" &&
				typeof( data.query.pages ) != "undefined"
			) {
				for ( var key in data.query.pages ) {
					if ( typeof( data.query.pages[ key ] ) != "undefined" &&
						typeof( data.query.pages[ key ].langlinks ) != "undefined" &&
						typeof( data.query.pages[ key ].langlinks[ 0 ] ) != "undefined" &&
						typeof( data.query.pages[ key ].langlinks[ 0 ][ "*" ] ) != "undefined"
					) {
						var trad = data.query.pages[ key ].langlinks[ 0 ][ "*" ];
						$( '#wpTextbox1' ).textSelection( 'encapsulateSelection', {
							pre: trad + "|"
						} );
						document.getElementById( 'wpTextbox1' ).selectionStart = selStart + trad.length;
						document.getElementById( 'wpTextbox1' ).selectionEnd = selEnd + trad.length + 2;
						return;
					}
				}
			}
			var noLinkLabel = "[NO LINK]";
			$( '#wpTextbox1' ).textSelection( 'encapsulateSelection', {
				pre: "",
				post: noLinkLabel
			} );
			document.getElementById( 'wpTextbox1' ).selectionStart = selEnd;
			document.getElementById( 'wpTextbox1' ).selectionEnd = selEnd + noLinkLabel.length;
		} );
	}

	// setup hotkeys
	$( 'body' ).keydown( function( event ) {
		if ( !event.altKey && !event.shiftKey && event.ctrlKey && !event.metaKey ) {
			if ( event.which === 48 ) {
				event.preventDefault();
				mw.loader.using( [ 'oojs-ui-core', 'oojs-ui-widgets', 'oojs-ui-windows', 'mediawiki.widgets' ] )
					.done( showDialog )
					.fail( function() { console.error( 'Errore configurazione tradLink' ); } );
			} else if ( event.which >= 49 && event.which < 57 ) {
				event.preventDefault();
				tradLink( event.which - 49 );
			}
		}
	} );
}( mediaWiki, jQuery ) );

popupFixRedirs = true;
popupRedirAutoClick = 'wpPreview';
popupFixDabs = true;
popupDabsAutoClick = "wpPreview";