MediaWiki:Common.js: mudanças entre as edições

De Grêmiopédia, a enciclopédia do Grêmio
Ir para navegação Ir para pesquisar
(Criou página com '→‎Qualquer código JavaScript presente aqui será carregado por todos os usuários em cada página carregada.: /*jshint camelcase: true, curly: true, eqeqeq: true, immed: t...')
 
Sem resumo de edição
 
(39 revisões intermediárias por 3 usuários não estão sendo mostradas)
Linha 2: Linha 2:
/*jshint camelcase: true, curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, noempty: true, nonew: true, quotmark: single, trailing: true, undef: true, unused: true, bitwise: true, forin: true, regexp: true, strict: true, onevar: true, laxbreak: true */
/*jshint camelcase: true, curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, noempty: true, nonew: true, quotmark: single, trailing: true, undef: true, unused: true, bitwise: true, forin: true, regexp: true, strict: true, onevar: true, laxbreak: true */
/*global mediaWiki, jQuery */
/*global mediaWiki, jQuery */
// Esconde botões "Ver código-fonte" e "Ver histórico" para usuários anônimos
mw.loader.using(['mediawiki.user', 'mediawiki.util'], function () {
    $(document).ready(function () {
        if (!mw.user.isLoggedIn()) {
            // Remove botões visíveis diretamente (skins antigas ou personalizadas)
            $('#ca-viewsource, #ca-history').remove();
            // Observa mudanças no DOM para pegar botões que aparecem depois
            const observer = new MutationObserver(function () {
                // Remove itens do menu suspenso
                $('a[href*="action=history"], a[href*="action=edit"], a[href*="action=submit"]').each(function () {
                    const texto = $(this).text().toLowerCase();
                    if (texto.includes('histórico') || texto.includes('ver código-fonte')) {
                        $(this).closest('li').remove();
                    }
                });
            });
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
        }
    });
});
//carrocel de imagens de 3 segundos
mw.loader.using('jquery', function() {
    $(document).ready(function() {
        setInterval(function() {
            var slides = $("#slideshow .slide");
            slides.each(function(i) {
                if ($(this).css("display") === "block") {
                    $(this).css("display", "none");
                    var next = (i + 1) % slides.length;
                    slides.eq(next).css("display", "block");
                    return false;
                }
            });
        }, 3000); // Troca a cada 3 segundos
    });
});


( function ( mw, $ ) {
( function ( mw, $ ) {
Linha 76: Linha 119:


}( mediaWiki, jQuery ) );
}( mediaWiki, jQuery ) );
if (mw.config.get('wgPagename') === 'Usuário:Maicon_Silva/sandbox') {
    window.location.replace(mw.util.getUrl('Usuário:Maicon Silva/Testes'));
}
//testes lazy
document.addEventListener("DOMContentLoaded", function () {
    // Seleciona todas as imagens
    const images = document.querySelectorAll('img');
    images.forEach(function (img) {
        // Verifica se a imagem está dentro de um NavFrame
        if (img.closest('.NavFrame')) {
            // Remove o atributo 'loading="lazy"' das imagens dentro de NavFrame
            img.removeAttribute('loading');
        } else {
            // Garante que as imagens fora de NavFrame tenham lazy loading
            if (!img.hasAttribute('loading')) {
                img.setAttribute('loading', 'lazy');
            }
        }
    });
});
// proteger o código fonte
$(document).ready(function () {
  var viewSourceTab = $('#ca-viewsource');
  if (viewSourceTab.length) {
    var link = viewSourceTab.find('a');
    var label = link.text();
    var href = link.attr('href');
    // Cria novo item no menu lateral
    var newItem = $('<li><a href="' + href + '">' + label + '</a></li>');
    // Adiciona no menu lateral, em uma seção customizada
    var toolbox = $('#p-tb ul');
    if (!toolbox.length) {
      // Se não existir a toolbox, cria
      $('#mw-panel').append(
        '<div class="portal" role="navigation" id="p-custom" aria-labelledby="p-custom-label">' +
          '<h3 id="p-custom-label">Ações</h3>' +
          '<div class="body"><ul></ul></div></div>'
      );
      toolbox = $('#p-custom ul');
    }
    toolbox.append(newItem);
    // Remove a aba do topo
    viewSourceTab.remove();
  }
});
    // Começa código Giro
(function (mw, $) {
  'use strict';
  function normalizeKey(key) {
    return String(key).replace(/[^a-z0-9]/gi, '_');
  }
  function getRodadaFromHash(key) {
    var h = window.location.hash || '';
    var re = new RegExp('(?:^|[&#])rodada_' + key + '=([^&]+)', 'i');
    var m = h.match(re);
    return m ? decodeURIComponent(m[1]) : null;
  }
  function setRodadaInHash(key, value) {
    var hash = (window.location.hash || '').replace(/^#/, '');
    var parts = hash ? hash.split('&') : [];
    var found = false;
    parts = parts.map(function (p) {
      if (p.toLowerCase().indexOf(('rodada_' + key + '=').toLowerCase()) === 0) {
        found = true;
        return 'rodada_' + key + '=' + encodeURIComponent(value);
      }
      return p;
    });
    if (!found) {
      parts.push('rodada_' + key + '=' + encodeURIComponent(value));
    }
    window.location.hash = parts.filter(Boolean).join('&');
  }
  function renderRodada($box, rodada) {
    if (!rodada) return;
    $box.addClass('is-loading');
    new mw.Api().post({
      action: 'parse',
      format: 'json',
      contentmodel: 'wikitext',
      prop: 'text',
      disableeditsection: 1,
      disablelimitreport: 1,
      title: mw.config.get('wgPageName'),
      text: '{{' + rodada + '}}'
    }).then(function (data) {
      var html = data && data.parse && data.parse.text && data.parse.text['*'];
      $box.html(html || '<div>Falha ao renderizar</div>');
    }).catch(function (e) {
      $box.html('<div>Erro ao carregar rodada</div>');
      if (window.console) console.error(e);
    }).always(function () {
      $box.removeClass('is-loading');
    });
  }
  function boot() {
    var $boxes = $('.rodada-viewer');
    if (!$boxes.length) return;
    function loadOne($box) {
      var rawKey = $box.data('giro');
      var key = normalizeKey(rawKey);
      var rodada = getRodadaFromHash(key) || $box.data('rodada');
      renderRodada($box, rodada);
    }
    function loadAll() {
      $boxes.each(function () { loadOne($(this)); });
    }
    loadAll();
    $(window).on('hashchange', loadAll);
    $boxes.on('click', 'a', function (e) {
      var href = this.getAttribute('href') || '';
      if (href.indexOf('#rodada=') === 0) {
        e.preventDefault();
        var $box = $(this).closest('.rodada-viewer');
        var rawKey = $box.data('giro');
        var key = normalizeKey(rawKey);
        var rodadaNova = href.substring('#rodada='.length);
        setRodadaInHash(key, rodadaNova);
      }
    });
  }
  mw.loader.using(['mediawiki.api', 'jquery']).then(boot);
})(mediaWiki, jQuery);

Edição atual tal como às 13h40min de 18 de fevereiro de 2026

/* Qualquer código JavaScript presente aqui será carregado por todos os usuários em cada página carregada. */ /*jshint camelcase: true, curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, noempty: true, nonew: true, quotmark: single, trailing: true, undef: true, unused: true, bitwise: true, forin: true, regexp: true, strict: true, onevar: true, laxbreak: true */ /*global mediaWiki, jQuery */ // Esconde botões "Ver código-fonte" e "Ver histórico" para usuários anônimos mw.loader.using(['mediawiki.user', 'mediawiki.util'], function () { $(document).ready(function () { if (!mw.user.isLoggedIn()) { // Remove botões visíveis diretamente (skins antigas ou personalizadas) $('#ca-viewsource, #ca-history').remove(); // Observa mudanças no DOM para pegar botões que aparecem depois const observer = new MutationObserver(function () { // Remove itens do menu suspenso $('a[href*="action=history"], a[href*="action=edit"], a[href*="action=submit"]').each(function () { const texto = $(this).text().toLowerCase(); if (texto.includes('histórico') || texto.includes('ver código-fonte')) { $(this).closest('li').remove(); } }); }); observer.observe(document.body, { childList: true, subtree: true }); } }); }); //carrocel de imagens de 3 segundos mw.loader.using('jquery', function() { $(document).ready(function() { setInterval(function() { var slides = $("#slideshow .slide"); slides.each(function(i) { if ($(this).css("display") === "block") { $(this).css("display", "none"); var next = (i + 1) % slides.length; slides.eq(next).css("display", "block"); return false; } }); }, 3000); // Troca a cada 3 segundos }); }); ( function ( mw, $ ) { 'use strict'; /** * Oculta botão editar da [[Wikipédia:Esplanada/propostas]] e da [[Wikipédia:Esplanada/geral]] * * @author: Helder (https://github.com/he7d3r) * @license: CC BY-SA 3.0 <https://creativecommons.org/licenses/by-sa/3.0/> */ function hideEditButton() { var temp = 'Template:Esplanada2/Preload'; if ( mw.config.get( 'wgUserLanguage' ) !== 'pt' ) { temp += '/en'; } $( '#ca-addsection' ).find( 'a' ).attr( 'href', mw.util.getUrl( mw.config.get( 'wgPageName' ), { action: 'edit', section: 'new', preload: temp } ) ); if ( mw.config.get( 'skin' ) === 'vector' ) { // Move o botão "editar" para o menu de ações $( '#p-cactions' ).removeClass( 'emptyPortlet' ).find( 'ul' ).append( $( '#ca-edit' ) ); } } /** * Parâmetros &withCSS= e &withJS= para a URL * * Permite que sejam testados scripts e folhas de estilos do domínio MediaWiki * sem precisar editar páginas ".css" ou ".js" pessoais * @source https://www.mediawiki.org/wiki/Snippets/Load_JS_and_CSS_by_URL * @revision 2016-03-26 */ mw.loader.using( ['mediawiki.util', 'mediawiki.notify'], function () { var extraCSS = mw.util.getParamValue( 'withCSS' ), extraJS = mw.util.getParamValue( 'withJS' ); if ( extraCSS ) { if ( /^MediaWiki:[^&<>=%#]*\.css$/.test( extraCSS ) ) { mw.loader.load( '/w/index.php?title=' + extraCSS + '&action=raw&ctype=text/css', 'text/css' ); } else { mw.notify( 'Só são permitidas páginas do domínio MediaWiki.', { title: 'Valor withCSS inválido' } ); } } if ( extraJS ) { if ( /^MediaWiki:[^&<>=%#]*\.js$/.test( extraJS ) ) { mw.loader.load( '/w/index.php?title=' + extraJS + '&action=raw&ctype=text/javascript' ); } else { mw.notify( 'Só são permitidas páginas do domínio MediaWiki.', { title: 'Valor withJS inválido' } ); } } } ); // Ocultar a barra de sumário das páginas de pedidos mw.loader.using( 'mediawiki.util', function () { if ( /Wikipédia:Pedidos\/(?!Outros|Revisão_de_ações_administrativas$)/.test( mw.config.get( 'wgPageName' ) ) && mw.util.getParamValue( 'section' ) === 'new' ) { $( '.mw-summary' ).hide(); } } ); // Scripts para páginas específicas if ( $.inArray( mw.config.get( 'wgPageName' ), [ 'Wikipédia:Esplanada/propostas', 'Wikipédia:Esplanada/geral' ] ) !== -1 ) { $( hideEditButton ); } }( mediaWiki, jQuery ) ); if (mw.config.get('wgPagename') === 'Usuário:Maicon_Silva/sandbox') { window.location.replace(mw.util.getUrl('Usuário:Maicon Silva/Testes')); } //testes lazy document.addEventListener("DOMContentLoaded", function () { // Seleciona todas as imagens const images = document.querySelectorAll('img'); images.forEach(function (img) { // Verifica se a imagem está dentro de um NavFrame if (img.closest('.NavFrame')) { // Remove o atributo 'loading="lazy"' das imagens dentro de NavFrame img.removeAttribute('loading'); } else { // Garante que as imagens fora de NavFrame tenham lazy loading if (!img.hasAttribute('loading')) { img.setAttribute('loading', 'lazy'); } } }); }); // proteger o código fonte $(document).ready(function () { var viewSourceTab = $('#ca-viewsource'); if (viewSourceTab.length) { var link = viewSourceTab.find('a'); var label = link.text(); var href = link.attr('href'); // Cria novo item no menu lateral var newItem = $('<li><a href="' + href + '">' + label + '</a></li>'); // Adiciona no menu lateral, em uma seção customizada var toolbox = $('#p-tb ul'); if (!toolbox.length) { // Se não existir a toolbox, cria $('#mw-panel').append( '<div class="portal" role="navigation" id="p-custom" aria-labelledby="p-custom-label">' + '<h3 id="p-custom-label">Ações</h3>' + '<div class="body"><ul></ul></div></div>' ); toolbox = $('#p-custom ul'); } toolbox.append(newItem); // Remove a aba do topo viewSourceTab.remove(); } }); // Começa código Giro (function (mw, $) { 'use strict'; function normalizeKey(key) { return String(key).replace(/[^a-z0-9]/gi, '_'); } function getRodadaFromHash(key) { var h = window.location.hash || ''; var re = new RegExp('(?:^|[&#])rodada_' + key + '=([^&]+)', 'i'); var m = h.match(re); return m ? decodeURIComponent(m[1]) : null; } function setRodadaInHash(key, value) { var hash = (window.location.hash || '').replace(/^#/, ''); var parts = hash ? hash.split('&') : []; var found = false; parts = parts.map(function (p) { if (p.toLowerCase().indexOf(('rodada_' + key + '=').toLowerCase()) === 0) { found = true; return 'rodada_' + key + '=' + encodeURIComponent(value); } return p; }); if (!found) { parts.push('rodada_' + key + '=' + encodeURIComponent(value)); } window.location.hash = parts.filter(Boolean).join('&'); } function renderRodada($box, rodada) { if (!rodada) return; $box.addClass('is-loading'); new mw.Api().post({ action: 'parse', format: 'json', contentmodel: 'wikitext', prop: 'text', disableeditsection: 1, disablelimitreport: 1, title: mw.config.get('wgPageName'), text: '{{' + rodada + '}}' }).then(function (data) { var html = data && data.parse && data.parse.text && data.parse.text['*']; $box.html(html || '<div>Falha ao renderizar</div>'); }).catch(function (e) { $box.html('<div>Erro ao carregar rodada</div>'); if (window.console) console.error(e); }).always(function () { $box.removeClass('is-loading'); }); } function boot() { var $boxes = $('.rodada-viewer'); if (!$boxes.length) return; function loadOne($box) { var rawKey = $box.data('giro'); var key = normalizeKey(rawKey); var rodada = getRodadaFromHash(key) || $box.data('rodada'); renderRodada($box, rodada); } function loadAll() { $boxes.each(function () { loadOne($(this)); }); } loadAll(); $(window).on('hashchange', loadAll); $boxes.on('click', 'a', function (e) { var href = this.getAttribute('href') || ''; if (href.indexOf('#rodada=') === 0) { e.preventDefault(); var $box = $(this).closest('.rodada-viewer'); var rawKey = $box.data('giro'); var key = normalizeKey(rawKey); var rodadaNova = href.substring('#rodada='.length); setRodadaInHash(key, rodadaNova); } }); } mw.loader.using(['mediawiki.api', 'jquery']).then(boot); })(mediaWiki, jQuery);