MediaWiki:Common.js

De WikiDex
Ir a la navegaciónIr a la búsqueda

Nota: Después de publicar, quizás necesite actualizar la caché de su navegador para ver los cambios.

  • Firefox/Safari: Mantenga presionada la tecla Shift mientras pulsa el botón Actualizar, o presiona Ctrl+F5 o Ctrl+R (⌘+R en Mac)
  • Google Chrome: presione Ctrl+Shift+R (⌘+Shift+R en Mac)
  • Internet Explorer/Edge: mantenga presionada Ctrl mientras pulsa Actualizar, o presione Ctrl+F5
  • Opera: Presiona Ctrl+F5.
/* <pre> v271 */

/* Control de errores */
function trataError(e) {
	setTimeout(function(err) {
		return function() {
			throw err;
		};
	}(e), 10);
}

/* Esta función evita que se detenga la carga de otros scripts en el onload si uno de ellos falla*/
function safeOnLoadHook(fn) {
	if ($) {
		$(function() {
			try {
				fn();
			} catch(e) {
				typeof(window.trataError)=='function'&&trataError(e);
			}
		});
	}
}

window.commonjstype = window.commonjstype || 'wiki';
if ( window.commonjstype != 'wiki' ) {
    window.skipcommonjswiki = true;
}

window.bodyContentId = 'bodyContent';

// Quitar ?mobileaction=toggle_view_mobile de la URL
(function() {
	try {
		var loc, q = '?mobileaction=toggle_view_mobile';
		if (window.location.search == q) {
			loc = window.location.href.replace(q, '');
			history.replaceState({}, document.title, loc);
		}
	} catch (e) {}
})();

/* === Sortable corregido/mejorado para ordenar imágenes === */
// Buscar celdas con imagen o ref (limitado a primer elemento hijo, por rendimiento) y agrega un data-sort-value ignorando el ref y traduciendo correctamente la imagen
var tablesorter_fixImagenesRefs = function() {
	var cache = [], text, $node, cn, ee, cambios = false, i, j;
	for ( i = 1; i < this.rows.length; i++ ) {
		cache[i] = [];
		for ( j = 0; j < this.rows[i].cells.length; j++ ) {
			if ( $( '> a.image,> sup.reference', this.rows[i].cells[j] ).length ) {
				if ( this.rows[i].cells[j].getAttribute( 'data-sort-value' ) ) {
					// Skip existing
					continue;
				}
				text = '';
				cn = this.rows[i].cells[j].childNodes;
				for ( ee = 0; ee < cn.length; ee++ ) {
					if ( cn[ee].nodeType == 3 ) {
						text += cn[ee].data;
					} else {
						$node = $( cn[ee] );
						if ( $node.is( 'a.image' ) ) {
							text += cn[ee].title;
						} else if ( ! $node.is( 'sup.reference' ) ) { // Nos saltamos los <ref>
							text += $node.text();
						}
					}
				}
				cache[i][j] = $.trim( text );
				cambios = cambios || ( cache[i][j] && true );
			}
		}
	}
	if ( !cambios ) {
		return;
	}
	for ( i = 1; i < this.rows.length; i++ ) {
		for ( j = 0; j < this.rows[i].cells.length; j++ ) {
			if ( cache[i][j] ) {
				this.rows[i].cells[j].setAttribute( 'data-sort-value', cache[i][j] );
			}
		}
	}
};

(typeof(window.safeOnLoadHook)=='function'?safeOnLoadHook:$)( function() {
    if (window.skipcommonjswiki) { return; }
	$( 'table.sortable', '#mw-content-text' ).each( function() {
		// Attach del evento en mousedown porque se ejecutará antes que el click del tablesorter
		// Una vez se ejecute el click, se guarda en caché los valores de columna, por lo que modificar el DOM después no funcionará
		$(this).find( 'th' ).on( 'mousedown.fixpending_sortimgref', function() {
			// Retiramos el evento para que no se vuelva a ejecutar
			var ts = $(this).closest( 'table.sortable' );
			ts.find( 'th' ).off( 'mousedown.fixpending_sortimgref' );
			tablesorter_fixImagenesRefs.call(ts[0]);
		} );
	} );
} );
/* == Herramientas de edición == */
var loadEditJS = function(){
	if (mw.config.get('wgAction', '') == 'edit' || mw.config.get('wgAction', '') == 'submit' ||
		mw.config.get('wgCanonicalSpecialPageName', '') == 'Upload' ||
		mw.config.get('wgCanonicalSpecialPageName', '') == 'MultiUpload')
	{
		mw.loader.using( 'user.options' ).then( function () {
			// This can be the string "0" if the user disabled the preference ([[phab:T54542#555387]])
			if ( mw.user.options.get( 'usebetatoolbar' ) == 1 ) {
				$.when(
					mw.loader.using( 'ext.wikiEditor' ), $.ready
				).then( function() {
					if (mw.loader.getState('ext.gadget.CharInsert')) {
						mw.loader.load('ext.gadget.CharInsert');
					}
				} );
			}
		} );
		
		// Cargar el editor de TemplateData en espacio de nombres Documentación_de_plantilla
		if ( mw.config.get('wgCanonicalNamespace') == 'Documentación_de_plantilla' &&
			mw.loader.getState('ext.templateDataGenerator.editTemplatePage') == 'registered' )
		{
			if ( $( '.tdg-editscreen-placeholder' ).length === 0 ) {
				$( '<div class="tdg-editscreen-placeholder">' ).prependTo( '#mw-content-text' );
			}
			mw.loader.load('ext.templateDataGenerator.editTemplatePage');
		}
		
		if (window.location.toString().indexOf('undo=') == -1 && window.location.toString().indexOf('undoafter=') == -1) {
			if (mw.config.get('wgNamespaceNumber', 0) === 0) {
				if (mw.loader.getState('ext.gadget.avisocuriosidades')) {
					mw.loader.load('ext.gadget.avisocuriosidades');
				}
			}
			if (mw.config.get('wgNamespaceNumber', 0) == 2 && window.location.toString().indexOf('action=edit') != -1) {
				if (mw.loader.getState('ext.gadget.disablefirstsubmit')) {
					mw.loader.load('ext.gadget.disablefirstsubmit');
				}
			}
		}
	}
};

if (!window.skipcommonjswiki) {
(typeof(window.safeOnLoadHook)=='function'?safeOnLoadHook:$)(loadEditJS);
}

/* == Acopla tablas ==
Para unir las filas en una sola tabla. [[MediaWiki:Mergetables.js]]
*/
var acopla_tablas = function(){
	switch(mw.config.get('wgPageName')){
		case 'Lista_de_Pokémon':
		case 'Lista_de_movimientos':
			if (mw.loader.getState('ext.gadget.mergetables')) {
				mw.loader.load('ext.gadget.mergetables');
			}
			break;
	}
};

if (!window.skipcommonjswiki) {
(typeof(window.safeOnLoadHook)=='function'?safeOnLoadHook:$)(acopla_tablas);
}

if (!window.skipcommonjswiki) {

if ((mw.config.get('wgAction') == 'view' || mw.config.get('wgAction') == 'edit' || mw.config.get('wgAction') == 'submit') && (mw.config.get('wgCanonicalSpecialPageName', '') != 'Recentchanges')) {
	(typeof(window.safeOnLoadHook)=='function'?safeOnLoadHook:$)(function() {
		if (mw.loader.getState('ext.gadget.imageswitcher')) {
			mw.loader.load('ext.gadget.imageswitcher');
		}
		if ( mw.loader.getState('ext.gadget.ZoomableMap') && mw.config.get( 'wgCategories', [] ).indexOf( 'Páginas que usan ZoomableMap' ) !== -1 ) {
			mw.loader.load('ext.gadget.ZoomableMap');
		}
		if ( mw.loader.getState('ext.gadget.MapaLPAInteractivo') && mw.config.get( 'wgCategories', [] ).indexOf( 'Páginas que usan MapaLPAInteractivo' ) !== -1 ) {
			mw.loader.load('ext.gadget.MapaLPAInteractivo');
		}
		if ( mw.loader.getState('ext.gadget.Mastodon') && mw.config.get( 'wgCategories', [] ).indexOf( 'Páginas que usan Mastodon' ) !== -1 ) {
			mw.loader.load('ext.gadget.Mastodon');
		}
	});
}

if (mw.config.get('wgCanonicalSpecialPageName', '') == 'Upload' || mw.config.get('wgCanonicalSpecialPageName', '') == 'MultiUpload') {
	(typeof(window.safeOnLoadHook)=='function'?safeOnLoadHook:$)(function() {
		if (mw.loader.getState('ext.gadget.uploadvalidator')) {
			mw.loader.load('ext.gadget.uploadvalidator');
		}
	});
}

if (mw.config.get('wgNamespaceNumber', 0) != -1) {
	(typeof(window.safeOnLoadHook)=='function'?safeOnLoadHook:$)(function() {
		if (mw.loader.getState('ext.gadget.SVGDirecto')) {
			mw.loader.load('ext.gadget.SVGDirecto');
		}
	});
}

}

// Impedir el renombrado de página de usuario
var disableUserpageMove = function() {
	var url = window.location.toString();
	var pn = mw.config.get('wgPageName', '');
	var pos = url.indexOf(pn);
	if (pos == -1) {
		url = decodeURIComponent(url);
	}
	pos = url.indexOf(pn);
	if (pos == -1) return; // fail :(
	var page = url.substr(url.indexOf(pn)+pn.length+1);
	pos = page.indexOf('?');
	if (pos != -1) {
		page = page.substr(0, pos);
	}
	pos = page.indexOf('/');
	if (pos != -1) {
		// Si hay barra es que se está trasladando una subpágina. Ok, lo permitimos
		return;
	}
	// Es página de usuario?
	var re_user = new RegExp('^(user|'+mw.config.get('wgFormattedNamespaces')['2']+'):', 'i');
	if (re_user.test(page)) {
		// Excluir admin y otros
		for (var i = 0; i < mw.config.get('wgUserGroups', []).length; i++) {
			if (mw.config.get('wgUserGroups')[i] == 'sysop' || mw.config.get('wgUserGroups')[i] == 'asistente' || mw.config.get('wgUserGroups')[i] == 'rollback') {
				return true;
			}
		}
		window.location = mw.config.get('wgArticlePath', '').replace('$1', 'Ayuda:Renombrar_mi_cuenta');
	}
};

if (mw.config.get('wgCanonicalSpecialPageName', '') == 'Movepage') {
	try {
		disableUserpageMove();
	} catch(e) {
		typeof(window.trataError)=='function'&&trataError(e);
	}
}

// Page tracker
(typeof(window.safeOnLoadHook)=='function'?safeOnLoadHook:$)(function() {
	if (window.gatracker || window.skipcommonjswiki) { return; }

	mw.loader.load( 'https://www.googletagmanager.com/gtag/js?id=G-CDVVKYSRQB' );

	window.dataLayer = window.dataLayer || [];
	function gtag(){dataLayer.push(arguments);}
	gtag('js', new Date());
	gtag('config', 'G-CDVVKYSRQB');

	window.gatracker = true;
});
// End Page tracker

// Problemas intermitentes de acceso a Cloudflare desde AS3352
( function( window, $ ) {
	
var imagesUrl = 'https://images.wikidexcdn.net/',
	altUrl = 'https://images2.wikidexcdn.net/',
	reUrl = /https:\/\/images\.wikidexcdn\.net\//g,
	_init = function() {
		var cachedStatus = window.localStorage.getItem( 'images-failrecv' );
		var ts = Date.now();
		if ( !cachedStatus ) {
			_checkImagesStatus();
			return;
		}
		var arStatus = cachedStatus.split( '|' );
		var savedTs = Number( arStatus[1] );
		if ( arStatus[0] === '1' ) {
			window.setTimeout( _replaceImages, 1000 );
		}
		// Cache for 10 min
		if ( isNaN( savedTs ) || ts - savedTs > 60000 * 10 ) {
			_checkImagesStatus();
			return;
		}
	},
	_checkImagesStatus = function() {
		var oReq = new XMLHttpRequest();
		oReq.timeout = 20000; // 20s
		oReq.open( 'GET', imagesUrl + 'conntest' );
		oReq.send();
		oReq.addEventListener( 'timeout' , _failedStatus );
		oReq.addEventListener( 'load' , _storeStatus );
	},
	_failedStatus = function() {
		_storeStatus( true );
		_replaceImages();
		var oReq = new XMLHttpRequest();
		oReq.open( 'GET', '/track/images-failrecv' );
		oReq.send();
	},
	_storeStatus = function( failure ) {
		window.localStorage.setItem( 'images-failrecv', ( (failure === true) ? '1' : '0' ) + '|' + Date.now() );
	},
	_replaceImages = function() {
		console.log( 'Se ha detectado problemas de acceso al dominio images.wikidexcdn.net. Se hará un reemplazo de las imágenes apuntando a images2' );
		var ii = document.querySelectorAll( 'img' );
		ii.forEach( function( img ) {
			if ( img.src && img.src.indexOf( imagesUrl ) === 0 ) {
				img.src = img.src.replace( imagesUrl, altUrl );
				if ( img.srcset ) {
					img.srcset = img.srcset.replace( reUrl, altUrl );
				}
			}
		} );
	};
	
	$( _init );
	
}( window, $ ) );

//</pre>