Diferencia entre revisiones de «MediaWiki:All.js»
De Inkipedia
m (Protegió «MediaWiki:All.js» ([Editar=Permitir solo administradores] (indefinido) [Trasladar=Permitir solo administradores] (indefinido))) |
m (Translation from English leftovers) |
||
Línea 360: | Línea 360: | ||
// Actualiza el elemento | // Actualiza el elemento | ||
slot.element.innerHTML = | slot.element.innerHTML = | ||
now >= slot.end ? " | now >= slot.end ? "Concluido" : | ||
now >= slot.start ? " | now >= slot.start ? "Ahora - " + formatDateTime(slot.end) : | ||
formatDateTime(slot.start) | formatDateTime(slot.start) | ||
; | ; |
Revisión del 13:10 8 abr 2022
/* Cualquier JavaScript aquí se cargará para todos los usuarios tanto en el escritorio como en el móvil */ /* strawpoll.me */ mw.loader.load('//splatoonwiki.org/wiki/MediaWiki:StrawpollIntegrator.js?action=raw&ctype=text/javascript') /* strawpoll.com */ mw.loader.load('//splatoonwiki.org/wiki/MediaWiki:StrawpollIntegrator2.js?action=raw&ctype=text/javascript') // ================================================================================ // JS/CSS específicos de la página // ================================================================================ //Comprueba los archivos específicos de la página $(function () { var url = new URL(window.location.href); var action = url.searchParams.get("action") if (action === null || action === "view" || action === "submit") { mw.loader.using("mediawiki.api", function () { var skin = mw.config.get("skin"), page = mw.config.get("wgPageName"), user = mw.config.get("wgUserName"); var pages = [ ['MediaWiki:Common.js/' + page + ".js", "js"], ['MediaWiki:Common.css/' + page + ".css", "css"], ['MediaWiki:' + skin + '.js/' + page + ".js", "js"], ['MediaWiki:' + skin + '.css/' + page + ".css", "css"] ]; if (user != null) pages.push( ['User:' + user + '/common.js/' + page + ".js", "js"], ['User:' + user + '/common.css/' + page + ".css", "css"], ['User:' + user + '/' + skin + '.js/' + page + ".js", "js"], ['User:' + user + '/' + skin + '.css/' + page + ".css", "css"] ); pages.forEach(function (el) { if (el[1] == "js") { if (new URL(window.location).searchParams.get("disable-page-js") != null) return; mw.loader.load('/w/index.php?title=' + encodeURIComponent(el[0]) + '&action=raw&ctype=text/javascript'); } else { if (new URL(window.location).searchParams.get("disable-page-css") != null) return; mw.loader.load('/w/index.php?title=' + encodeURIComponent(el[0]) + '&action=raw&ctype=text/css', 'text/css'); } }); }); } }); // ================================================================================ // Función de sustitución del nombre de usuario para [[Template:USERNAME]] // ================================================================================ // Inserta el nombre de usuario en <span class="insertusername"></span>. // Desactivar estableciendo disableUsernameReplace = true. jQuery(function($) { if (typeof(disableUsernameReplace) != 'undefined' && disableUsernameReplace) return; var username = mw.config.get('wgUserName'); if (username == null) return; $('.insertusername').text(username); }); // ================================================================================ // Función de sustitución de Editcount para [[Template:EDITCOUNT]] // ================================================================================ // Inserta el recuento de ediciones en <span class="inserteditcount"></span> jQuery(function($) { var userEditCount = mw.config.get('wgUserEditCount'); if (userEditCount == null) return; $('.inserteditcount').text(userEditCount); }); // ================================================================================ // Función de sustitución de la fecha de registro para [[Template:REGISTRATIONDATE]] // ================================================================================ // Inserta la fecha de registro en <span class="insertregistrationdate"></span> jQuery(function($) { var userRegistrationDate = mw.config.get('wgUserRegistration'); if (userRegistrationDate == null) return; var d = new Date(0); // Sets the date to the epoch d.setUTCMilliseconds(userRegistrationDate); $('.insertregistrationdate').text(d.toLocaleString()); }); /////////////////////////////////////////////////////////////////////////////// // Funciones de la utilidad de programación // /////////////////////////////////////////////////////////////////////////////// // Avanza una marca de tiempo al siguiente múltiplo de 2 horas function advanceDateTime(time) { var ret = new Date(time.getTime()); ret.setMinutes(0); ret.setTime(ret.getTime() + 3600000 * ( ret.getUTCHours() & 1 ? 1 : 2 )); return ret; } // Formatea una marca de tiempo como una cadena en tiempo local function formatDateTime(time) { var ret = time.getDate() + " " + [ "Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic" ][time.getMonth()] + " " + zeroPad(time.getHours(), 2) + ":" + zeroPad(time.getMinutes(), 2) ; return ret; } // Analiza una cadena de fecha UTC en el formato "MMM dd hh:mm YYYY", el año al final de la cadena es opcional y reemplaza el argumento del año si se proporciona function parseDateTime(text, year) { text = text.split(/[\s:]+/); if(parseInt(text[4]) != NaN && parseInt(text[4]) < 9999 && parseInt(text[4]) >= 1970) year = text[4]; return new Date(Date.UTC( year, { ene: 0, feb: 1, mar: 2, abr: 3, may: 4, jun: 5, jul: 6, ago: 7, sep: 8, oct: 9, nov: 10, dic: 11 }[text[0].toLowerCase()], parseInt(text[1]), // Día parseInt(text[2]), // Horas parseInt(text[3]), // Minutos 0, 0 // Segundos, milisegundos )); } // Convierte la última cadena obtenida en un objeto Date function parseFetched(now, text) { var ret = parseDateTime(text, now.getUTCFullYear()); if (now < ret) // Cuentas del límite del año ret.setUTCFullYear(ret.getUTCFullYear() - 1); return ret; } // Convierte una cadena de programación en un objeto Date function parseSchedule(fetched, text) { var ret = parseDateTime(text, fetched.getUTCFullYear()); if (ret.getTime() < fetched.getTime() - 8640000000) ret.setUTCFullYear(ret.getUTCFullYear() + 1); return ret; } // Calcula el tiempo restante hasta una marca de tiempo dada, como una cadena function timeUntil(now, target) { target = target.getTime() - now.getTime(); target = Math.floor(target % 7200000 / 1000); var seconds = zeroPad(target % 60, 2); var minutes = zeroPad(Math.floor(target / 60) % 60, 2); var hours = Math.floor(target / 3600); return hours + ":" + minutes + ":" + seconds; } // Rellena un número con ceros a la izquierda function zeroPad(number, digits) { number = "" + number; while (number.length < digits) number = "0" + number; return number; } /////////////////////////////////////////////////////////////////////////////// // Clase BattleSchedule // /////////////////////////////////////////////////////////////////////////////// // Mantiene la actualización automática de los elementos del calendario de Ink Battle // Constructor de objetos var BattleSchedule = function() { // Inicializa los campos de la instancia this.lblNow = document.getElementById("battle1"); this.lblNext = document.getElementById("battle2"); this.lblFetched = document.getElementById("battleFetched"); this.prev = false; // Comprobación de errores if (!this.lblFetched) return; // No schedule data // Obtener las marcas de tiempo actuales y las últimas obtenidas var now = new Date(); var fetched = parseFetched(now, this.lblFetched.innerHTML); // Determina la marca de tiempo de las siguientes dos rotaciones this.next = advanceDateTime(fetched); this.later = advanceDateTime(this.next); // Actualiza la visualización inicial this.onTick(now); this.lblFetched.innerHTML = formatDateTime(fetched); // Programa actualizaciones periódicas var that = this; this.timer = setInterval(function() { that.onTick(new Date()); }, 1000); }; // Manipulador de actualizaciones periódicas BattleSchedule.prototype.onTick = function(now) { // Determina cuándo la fila "Ahora" entra en el pasado if (now >= this.next && !this.prevNow) { this.prev = true; this.lblNow.innerHTML = "Anteriormente"; } // Determina cuando la fila "Siguiente" entra en el pasado if (now >= this.later && !this.prevNext) { this.lblNext.innerHTML = "Anteriormente"; clearInterval(this.timer); return; } // Muestra el tiempo hasta la siguiente rotación this.lblNext.innerHTML = (this.prev ? "Ahora, por otros " : "Siguiente, en ") + timeUntil(now, this.prev ? this.later : this.next) ; }; new BattleSchedule(); /////////////////////////////////////////////////////////////////////////////// // Clase SalmonSchedule // /////////////////////////////////////////////////////////////////////////////// // Mantiene la actualización automática de los elementos del calendario de Salmon Run // Constructor de objetos var SalmonSchedule = function() { // Obteiene las marcas de tiempo actuales y las últimas obtenidas var lblFetched = document.getElementById("salmonFetched"); if (!lblFetched) return; // Sin horario var now = new Date(); var fetched = parseFetched(now, lblFetched.innerHTML); // Inicializa los campos de la instancia this.slots = [ this.parse(document.getElementById("salmon1"), fetched), this.parse(document.getElementById("salmon2"), fetched), ]; // Actualiza la visualización inicial this.onTick(now); lblFetched.innerHTML = formatDateTime(fetched); // Programa actualizaciones periódicas var that = this; this.timer = setInterval(function() { that.onTick(new Date()); }, 1000); }; // Manejador de actualización periódica SalmonSchedule.prototype.onTick = function(now) { // Ciclo a través de las ranuras for (var x = 0; x < this.slots.length; x++) { var slot = this.slots[x]; if (slot.prev) continue; // Saltar esta ranura // Determina cuándo esta ranura debe dejar de actualizarse slot.prev = now >= slot.end; // Actualiza el elemento slot.element.innerHTML = now >= slot.end ? "Anteriormente" : now >= slot.start ? "Ahora - " + formatDateTime(slot.end) : formatDateTime(slot.start) + " - " + formatDateTime(slot.end) ; } // Desprograma el temporizador if (this.slots[this.slots.length - 1].prev) clearInterval(this.timer); }; // Analiza una única ranura de programación de Salmon Run SalmonSchedule.prototype.parse = function(element, fetched) { var text = element.innerHTML; return { element: element, start: parseSchedule(fetched, text.substring( 0, 12)), end: parseSchedule(fetched, text.substring(15, 27)), prev: false }; } new SalmonSchedule(); /////////////////////////////////////////////////////////////////////////////// // Clase ShopSchedule // /////////////////////////////////////////////////////////////////////////////// // Mantiene la actualización automática de los elementos del calendario de la tienda SplatNet 2 // Constructor de objetos var ShopSchedule = function() { var lblFetched = document.getElementById("shopFetched"); if (!lblFetched) return; // Sin horario // Obtiene las marcas de tiempo actuales y las últimas obtenidas var now = new Date(); var fetched = parseFetched(now, lblFetched.innerHTML); // Actualiza la visualización inicial lblFetched.innerHTML = formatDateTime(fetched); }; new ShopSchedule(); /////////////////////////////////////////////////////////////////////////////// // Clase SplatfestSchedule // /////////////////////////////////////////////////////////////////////////////// // Mantiene la actualización automática de los elementos del calendario del Splatfest // Constructor de objetos var SplatfestSchedule = function() { // Inicializa los campos de la instancia var now = new Date(); this.slots = [ this.parse(document.getElementById("splatfest1"), now), this.parse(document.getElementById("splatfest2"), now), this.parse(document.getElementById("splatfest3"), now) ]; // Actualiza la visualización inicial this.onTick(now); // Programa actualizaciones periódicas var that = this; this.timer = setInterval(function() { that.onTick(new Date()); }, 1000); }; // Manipulador de actualizaciones periódicas SplatfestSchedule.prototype.onTick = function(now) { // Ciclo a través de las ranuras for (var x = 0; x < this.slots.length; x++) { var slot = this.slots[x]; if (slot.prev) continue; // Saltar esta ranura // Determina cuando esta ranura debe dejar de actualizarse slot.prev = now >= slot.end; // Actualiza el elemento slot.element.innerHTML = now >= slot.end ? "Concluido" : now >= slot.start ? "Ahora - " + formatDateTime(slot.end) : formatDateTime(slot.start) ; } // Desprograma el temporizador if (this.slots[this.slots.length - 1].prev) clearInterval(this.timer); }; // Analiza una sola ranura de Splatfest schdule SplatfestSchedule.prototype.parse = function(element, now) { // Comprobación de errores if (!element) return { prev: true }; // Determina la hora actual y las marcas de tiempo de inicio y fin var start = parseDateTime(element.innerHTML, now.getUTCFullYear()); return { element: element, start: start, end: new Date(start.getTime() + 172800000), prev: false }; }; new SplatfestSchedule(); // ================================================================================ // MediaLoader - Evitar que el audio se cargue hasta que se haga clic // Version 2 (19.04.2020) // ================================================================================ window.MediaLoader = {}; window.MediaLoader.FileCache = {}; function MLGetFileFromName(name){ return new Promise(function(k,no){ if(window.MediaLoader.FileCache[name] == null){ new mw.Api().get({ "action": "parse", "format": "json", "text": "[["+name+"]]", "prop": "text", "contentmodel": "wikitext" }).then(function(file){ var filetext = $($.parseHTML(file.parse.text["*"])).find('p').html(); window.MediaLoader.FileCache[name] = filetext; k(filetext); },no); } else k(window.MediaLoader.FileCache[name]); }) } mw.loader.using("mediawiki.api", function(){ $(".MediaLoader").each(function(){ $(this).data("state", "unloaded"); var children = $(this).children(); if(children.length < 1){ console.error("[MediaLoader] Error P1"); return; } var child = $(children[0]); child.find(".MediaLoader-text").click(function(){ var parent = $(this).parent().parent(); try{ if(parent.data("state") == "unloaded"){ parent.data("state", "busy"); $(this).text("Loading..."); MLGetFileFromName(parent.data("file")).then(function(filetext){ parent.find(".MediaLoader-file").html(filetext); parent.find(".MediaLoader-text").text("Unload "+parent.data("name")); parent.data("state", "loaded"); }, console.error) } else if(parent.data("state") == "loaded"){ parent.find(".MediaLoader-file").html(""); $(this).text("Load "+parent.data("name")); parent.data("state", "unloaded"); } } catch(ex){ console.error(ex); parent.data("state", "error"); $(this).text("An unexpected error has occured"); parent.find(".MediaLoader-file").html("<a></a>"); parent.find(".MediaLoader-file").children("a").attr("href", "//splatoonwiki.org/wiki/"+parent.data("file")) parent.find(".MediaLoader-file").children("a").text(parent.data("name")) $(this).css("cursor", ""); } }) child.find(".MediaLoader-text").text("Load "+$(this).data("name")); child.find(".MediaLoader-text").addClass("noselect"); child.find(".MediaLoader-text").css("cursor", "pointer"); child.find(".MediaLoader-file").addClass("noselect"); }) $(".MediaLoadAll").each(function(){ var children = $(this).children(); if(children.length < 2){ console.error("[MediaLoadAll] Error P1"); return; } children.click(function(){ var parent = $(this).parent(); try{ var load = $(this).hasClass("MediaLoadAll-load"); $(parent.data("group") != "{{{group}}}" ? '.MediaLoader[data-group="'+parent.data("group")+'"]' : ".MediaLoader").each(function(){ if(($(this).data("state") == "unloaded" && load) || ($(this).data("state") == "loaded" && !load)) $(this).find(".MediaLoader-text").click(); }) } catch(ex){ console.error(ex); $(this).text("An unexpected error has occured"); $(this).css("cursor", ""); } }) $(this).css("display", "") children.filter(".MediaLoadAll-load").text("Load all "+$(this).data("name")); children.filter(".MediaLoadAll-unload").text("Unload all "+$(this).data("name")); children.addClass("noselect"); children.css("cursor", "pointer"); }) })