Difference between revisions of "MediaWiki:Common.js"

From XilePK - Ragnarok Online Server
Jump to navigation Jump to search
Line 1: Line 1:
/* Any JavaScript here will be loaded for all users on every page load. */
 
 
$(document).ready(function() {
 
  $(document).on('click', '.warp-copy', function() {
 
    var textToCopy = $(this).attr('data-copy');
 
   
 
    var tempInput = document.createElement('textarea');
 
    tempInput.value = textToCopy;
 
    document.body.appendChild(tempInput);
 
    tempInput.select();
 
    document.execCommand('copy');
 
    document.body.removeChild(tempInput);
 
   
 
    var originalColor = $(this).css('color');
 
    $(this).css('color', 'green');
 
    var self = this;
 
    setTimeout(function() {
 
      $(self).css('color', originalColor);
 
    }, 500);
 
  });
 
});
 
 
 
/* Auto-expand sections when clicking anchored links */
 
/* Auto-expand sections when clicking anchored links */
 
$(function() {
 
$(function() {
Line 117: Line 95:
 
});
 
});
  
 +
// Função para melhorar a rolagem para âncoras
 
$(document).ready(function() {
 
$(document).ready(function() {
    // Verifica se há um fragmento na URL (parte após #)
+
  // Manipular cliques nos tiles da página principal
    if(window.location.hash) {
+
  $('.mainpage-contents .tile-halves a').click(function(e) {
        // Espera um pequeno tempo para garantir que a página está carregada
+
    var targetId = $(this).attr('href');
        setTimeout(function() {
 
            // Calcula a posição do elemento
 
            var targetElement = $(window.location.hash);
 
            if(targetElement.length) {
 
                // Obtém a posição do elemento
 
                var targetOffset = targetElement.offset().top;
 
                // Adiciona um offset para compensar qualquer header fixo
 
                targetOffset = targetOffset - 50; // Ajuste este valor conforme necessário
 
               
 
                // Rola a página até o elemento
 
                $('html, body').animate({
 
                    scrollTop: targetOffset
 
                }, 500);
 
            }
 
        }, 300);
 
    }
 
 
      
 
      
     // Corrige também os cliques em links para âncoras
+
     // Verificar se é um link para âncora
     $('a[href^="#"]').click(function(e) {
+
     if (targetId && targetId.startsWith('#')) {
         var targetHash = $(this).attr('href');
+
      e.preventDefault();
         var targetElement = $(targetHash);
+
     
 +
      // Remover o # do início
 +
      var sectionId = targetId.substring(1);
 +
     
 +
      // Tentar encontrar a seção pelo ID ou pelo título
 +
      var target = $('#' + sectionId);
 +
      if (target.length === 0) {
 +
        // Tentar encontrar pelo título da seção (h2)
 +
         target = $('h2:contains("' + sectionId.replace(/_/g, ' ') + '")');
 +
      }
 +
     
 +
      // Se encontrou algo, rolar até lá
 +
      if (target.length > 0) {
 +
         $('html, body').animate({
 +
          scrollTop: target.offset().top - 70 // Ajuste este valor conforme necessário
 +
        }, 500);
 
          
 
          
         if(targetElement.length) {
+
         // Atualizar a URL sem recarregar a página
            e.preventDefault();
+
        history.pushState(null, null, targetId);
           
+
      }
            // Obtém a posição do elemento
+
    }
            var targetOffset = targetElement.offset().top;
+
  });
            // Adiciona um offset para compensar qualquer header fixo
+
 
            targetOffset = targetOffset - 50; // Ajuste este valor conforme necessário
+
  // Também processar âncoras na URL quando a página carrega
           
+
  if (window.location.hash) {
            // Rola a página até o elemento
+
    setTimeout(function() {
            $('html, body').animate({
+
      var hash = window.location.hash;
                scrollTop: targetOffset
+
      var sectionId = hash.substring(1);
            }, 500);
+
     
           
+
      var target = $('#' + sectionId);
            // Atualiza a URL sem recarregar a página
+
      if (target.length === 0) {
            history.pushState(null, null, targetHash);
+
        target = $('h2:contains("' + sectionId.replace(/_/g, ' ') + '")');
        }
+
      }
    });
+
     
 +
      if (target.length > 0) {
 +
        $('html, body').animate({
 +
          scrollTop: target.offset().top - 70
 +
        }, 500);
 +
      }
 +
    }, 300);
 +
  }
 
});
 
});

Revision as of 17:08, 29 April 2025

/* Auto-expand sections when clicking anchored links */
$(function() {
  // Função principal para executar quando a página terminar de carregar
  function initializeAnchorExpansion() {
    // Se existir um hash na URL quando a página carrega
    if (window.location.hash) {
      var hash = window.location.hash;
      console.log("Página carregada com hash: " + hash);
      expandSectionForAnchor(hash);
    }
    
    // Lidar com cliques em links âncora dentro da página
    $(document).on('click', 'a[href^="#"]', function(event) {
      var hash = $(this).attr('href');
      console.log("Clique em link interno: " + hash);
      expandSectionForAnchor(hash);
    });
  }
  
  // Função para expandir seções contendo uma âncora específica
  function expandSectionForAnchor(hash) {
    // Remover qualquer caractere # do início do hash se existir
    if (hash.startsWith('#')) {
      hash = hash.substring(1);
    }
    
    console.log("Procurando elemento com ID: " + hash);
    
    // Tentar encontrar o elemento com o ID especificado
    var targetElement = $('#' + hash);
    if (targetElement.length) {
      console.log("Elemento encontrado!");
      
      // Encontrar todas as seções colapsáveis que contêm o elemento
      var collapsibleSections = targetElement.parents('.mw-collapsible.mw-collapsed');
      console.log("Seções colapsáveis encontradas: " + collapsibleSections.length);
      
      // Se o elemento estiver dentro de seções colapsáveis
      if (collapsibleSections.length > 0) {
        // Expandir cada seção de fora para dentro
        collapsibleSections.each(function() {
          var $section = $(this);
          console.log("Expandindo seção");
          $section.removeClass('mw-collapsed');
          
          // Clicar no botão de expansão ou mudar diretamente a classe
          var $toggle = $section.find('.mw-collapsible-toggle').first();
          if ($toggle.length) {
            $toggle.click();
          } else {
            // Tentar forçar a expansão manipulando classes diretamente
            $section.find('.mw-collapsible-content').show();
          }
        });
        
        // Também verificar se o próprio elemento está em um colapsível
        var directCollapsible = targetElement.closest('.mw-collapsible.mw-collapsed');
        if (directCollapsible.length) {
          console.log("Expandindo o contêiner direto");
          directCollapsible.removeClass('mw-collapsed');
          var $toggle = directCollapsible.find('.mw-collapsible-toggle').first();
          if ($toggle.length) {
            $toggle.click();
          } else {
            directCollapsible.find('.mw-collapsible-content').show();
          }
        }
      }
      
      // Rolar até o elemento imediatamente
      console.log("Rolando até o elemento");
      $('html, body').animate({
        scrollTop: targetElement.offset().top - 100
      }, 200);
    } else {
      console.log("Elemento com ID '" + hash + "' não encontrado");
    }
  }

  // Inicializar na carga da página
  initializeAnchorExpansion();
  
  // Também adicionar um observador para o evento mw.hook que é disparado quando o conteúdo é atualizado
  if (typeof mw !== 'undefined' && mw.hook) {
    mw.hook('wikipage.content').add(function() {
      console.log("Conteúdo da Wiki atualizado, reinicializando manipuladores de âncora");
      initializeAnchorExpansion();
      
      // Se houver um hash, tentar expandir após o conteúdo ter sido carregado
      if (window.location.hash) {
        expandSectionForAnchor(window.location.hash);
      }
    });
  }
});

// Função para melhorar a rolagem para âncoras
$(document).ready(function() {
  // Manipular cliques nos tiles da página principal
  $('.mainpage-contents .tile-halves a').click(function(e) {
    var targetId = $(this).attr('href');
    
    // Verificar se é um link para âncora
    if (targetId && targetId.startsWith('#')) {
      e.preventDefault();
      
      // Remover o # do início
      var sectionId = targetId.substring(1);
      
      // Tentar encontrar a seção pelo ID ou pelo título
      var target = $('#' + sectionId);
      if (target.length === 0) {
        // Tentar encontrar pelo título da seção (h2)
        target = $('h2:contains("' + sectionId.replace(/_/g, ' ') + '")');
      }
      
      // Se encontrou algo, rolar até lá
      if (target.length > 0) {
        $('html, body').animate({
          scrollTop: target.offset().top - 70 // Ajuste este valor conforme necessário
        }, 500);
        
        // Atualizar a URL sem recarregar a página
        history.pushState(null, null, targetId);
      }
    }
  });
  
  // Também processar âncoras na URL quando a página carrega
  if (window.location.hash) {
    setTimeout(function() {
      var hash = window.location.hash;
      var sectionId = hash.substring(1);
      
      var target = $('#' + sectionId);
      if (target.length === 0) {
        target = $('h2:contains("' + sectionId.replace(/_/g, ' ') + '")');
      }
      
      if (target.length > 0) {
        $('html, body').animate({
          scrollTop: target.offset().top - 70
        }, 500);
      }
    }, 300);
  }
});