Difference between revisions of "MediaWiki:Common.js"

From XilePK - Ragnarok Online Server
Jump to navigation Jump to search
 
(31 intermediate revisions by the same user not shown)
Line 1: Line 1:
/* Auto-expand sections when clicking anchored links */
+
/* Any JavaScript here will be loaded for all users on every page load. */
$(function() {
+
 
   // Função principal para executar quando a página terminar de carregar
+
$(document).ready(function() {
   function initializeAnchorExpansion() {
+
   // Função única para cópia de texto
     // Se existir um hash na URL quando a página carrega
+
   $(document).on('click', '.warp-copy', function(e) {
     if (window.location.hash) {
+
    e.preventDefault();
       var hash = window.location.hash;
+
    var textToCopy = $(this).attr('data-copy');
      console.log("Página carregada com hash: " + hash);
+
   
      expandSectionForAnchor(hash);
+
    // Cria elemento temporário para cópia
     }
+
    var tempInput = document.createElement('textarea');
 +
    tempInput.value = textToCopy;
 +
    document.body.appendChild(tempInput);
 +
    tempInput.select();
 +
    document.execCommand('copy');
 +
    document.body.removeChild(tempInput);
 +
   
 +
     // Adiciona classe para feedback visual
 +
    var $element = $(this);
 +
    $element.addClass('copied');
 +
    setTimeout(function() {
 +
      $element.removeClass('copied');
 +
    }, 2000);
 +
  });
 +
 
 +
  // Adicionar funcionalidade às imagens dos NPCs
 +
  function initImageCopy() {
 +
     $('.tile-top.tile-image a').each(function() {
 +
       var $link = $(this);
 +
      if (!$link.hasClass('warp-copy')) {
 +
        var npcId = $link.attr('href').replace('#','');
 +
        $link.addClass('warp-copy')
 +
            .attr('data-copy', '@warp ' + npcId)
 +
            .css('cursor', 'pointer');
 +
      }
 +
     });
 
      
 
      
     // Lidar com cliques em links âncora dentro da página
+
     // Aplicar tamanhos personalizados para imagens
     $(document).on('click', 'a[href^="#"]', function(event) {
+
     $('.tile-top.tile-image img').each(function() {
       var hash = $(this).attr('href');
+
       var $img = $(this);
       console.log("Clique em link interno: " + hash);
+
      var width = $img.data('width') || $img.attr('width');
      expandSectionForAnchor(hash);
+
       var height = $img.data('height') || $img.attr('height');
 +
     
 +
      if (width || height) {
 +
        $img.addClass('custom-size');
 +
        if (width) {
 +
          $img.css('--custom-width', width + 'px');
 +
        }
 +
        if (height) {
 +
          $img.css('--custom-height', height + 'px');
 +
        }
 +
      }
 
     });
 
     });
 +
  }
 +
 +
  // Inicializar ao carregar e em atualizações de conteúdo
 +
  initImageCopy();
 +
  if (typeof mw !== 'undefined' && mw.hook) {
 +
    mw.hook('wikipage.content').add(initImageCopy);
 +
  }
 +
 +
  /* Auto-expand sections when clicking anchored links */
 +
  console.log("Inicializando script para expandir seções com links âncora");
 +
 
 +
  // Handle initial page load with hash
 +
  if (window.location.hash) {
 +
    console.log("Página carregada com hash: " + window.location.hash);
 +
    setTimeout(function() {
 +
      expandSectionForAnchor(window.location.hash);
 +
    }, 300);
 
   }
 
   }
 
    
 
    
   // Função para expandir seções contendo uma âncora específica
+
   // Handle clicks on anchor links
   function expandSectionForAnchor(hash) {
+
   $(document).on('click', 'a[href^="#"]', function(event) {
     // Remover qualquer caractere # do início do hash se existir
+
     var hash = $(this).attr('href');
     if (hash.startsWith('#')) {
+
     console.log("Clique em link âncora: " + hash);
       hash = hash.substring(1);
+
    event.preventDefault();
 +
   
 +
    if (history.pushState) {
 +
       history.pushState(null, null, hash);
 +
    } else {
 +
      location.hash = hash;
 
     }
 
     }
 
      
 
      
     console.log("Procurando elemento com ID: " + hash);
+
    expandSectionForAnchor(hash);
 +
  });
 +
 
 +
  function expandSectionForAnchor(hash) {
 +
     console.log("Procurando e expandindo seção para âncora: " + hash);
 +
    var targetElement = $(hash);
 
      
 
      
    // Tentar encontrar o elemento com o ID especificado
 
    var targetElement = $('#' + hash);
 
 
     if (targetElement.length) {
 
     if (targetElement.length) {
       console.log("Elemento encontrado!");
+
       console.log("Elemento alvo encontrado");
 
        
 
        
      // Encontrar todas as seções colapsáveis que contêm o elemento
 
 
       var collapsibleSections = targetElement.parents('.mw-collapsible.mw-collapsed');
 
       var collapsibleSections = targetElement.parents('.mw-collapsible.mw-collapsed');
 +
      var directCollapsible = targetElement.closest('.mw-collapsible.mw-collapsed');
 +
     
 +
      if (directCollapsible.length) {
 +
        collapsibleSections = collapsibleSections.add(directCollapsible);
 +
      }
 +
     
 
       console.log("Seções colapsáveis encontradas: " + collapsibleSections.length);
 
       console.log("Seções colapsáveis encontradas: " + collapsibleSections.length);
 
        
 
        
      // Se o elemento estiver dentro de seções colapsáveis
 
 
       if (collapsibleSections.length > 0) {
 
       if (collapsibleSections.length > 0) {
        // Expandir cada seção de fora para dentro
 
 
         collapsibleSections.each(function() {
 
         collapsibleSections.each(function() {
           var $section = $(this);
+
           var section = $(this);
           console.log("Expandindo seção");
+
           console.log("Expandindo seção colapsável");
           $section.removeClass('mw-collapsed');
+
            
 +
          section.removeClass('mw-collapsed');
 +
          var toggleButton = section.find('.mw-collapsible-toggle').first();
 +
          if (toggleButton.length) {
 +
            console.log("Clicando no botão de expansão");
 +
            toggleButton.click();
 +
          }
 
            
 
            
           // Clicar no botão de expansão ou mudar diretamente a classe
+
           if (section.hasClass('wikitable')) {
          var $toggle = $section.find('.mw-collapsible-toggle').first();
+
             console.log("Expandindo tabela wikitable");
          if ($toggle.length) {
+
             section.find('tr:not(:first-child)').show();
             $toggle.click();
 
          } else {
 
            // Tentar forçar a expansão manipulando classes diretamente
 
             $section.find('.mw-collapsible-content').show();
 
 
           }
 
           }
 +
         
 +
          section.find('.mw-collapsible-content').show();
 
         });
 
         });
 
          
 
          
         // Também verificar se o próprio elemento está em um colapsível
+
         setTimeout(function() {
        var directCollapsible = targetElement.closest('.mw-collapsible.mw-collapsed');
+
           scrollToTarget(targetElement);
        if (directCollapsible.length) {
+
        }, 400);
           console.log("Expandindo o contêiner direto");
+
      } else {
          directCollapsible.removeClass('mw-collapsed');
+
        scrollToTarget(targetElement);
          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 {
 
     } else {
       console.log("Elemento com ID '" + hash + "' não encontrado");
+
       console.log("Elemento alvo não encontrado para hash: " + hash);
 
     }
 
     }
 
   }
 
   }
 
  // Inicializar na carga da página
 
  initializeAnchorExpansion();
 
 
    
 
    
   // Também adicionar um observador para o evento mw.hook que é disparado quando o conteúdo é atualizado
+
   function scrollToTarget(element) {
 +
    console.log("Rolando até o elemento alvo");
 +
    $('html, body').animate({
 +
      scrollTop: element.offset().top - 100
 +
    }, 200);
 +
  }
 +
 
 
   if (typeof mw !== 'undefined' && mw.hook) {
 
   if (typeof mw !== 'undefined' && mw.hook) {
 
     mw.hook('wikipage.content').add(function() {
 
     mw.hook('wikipage.content').add(function() {
       console.log("Conteúdo da Wiki atualizado, reinicializando manipuladores de âncora");
+
       console.log("Conteúdo da wiki atualizado");
      initializeAnchorExpansion();
 
     
 
      // Se houver um hash, tentar expandir após o conteúdo ter sido carregado
 
 
       if (window.location.hash) {
 
       if (window.location.hash) {
         expandSectionForAnchor(window.location.hash);
+
         setTimeout(function() {
 +
          expandSectionForAnchor(window.location.hash);
 +
        }, 300);
 
       }
 
       }
 
     });
 
     });
 
   }
 
   }
});
 
 
 
/* JavaScript para funcionalidade de cópia */
 
mw.hook('wikipage.content').add(function ($content) {
 
    // Adiciona funcionalidade aos elementos com a classe warp-copy
 
    $content.find('.warp-copy').on('click', function () {
 
        var textToCopy = $(this).attr('data-copy');
 
       
 
        // Cria um elemento temporário para copiar o texto
 
        var tempInput = document.createElement('textarea');
 
        tempInput.value = textToCopy;
 
        document.body.appendChild(tempInput);
 
        tempInput.select();
 
       
 
        try {
 
            // Executa o comando de cópia
 
            var successful = document.execCommand('copy');
 
           
 
            // Feedback visual temporário ao usuário
 
            var originalText = $(this).text();
 
            if (successful) {
 
                // Altera o texto do tooltip para "Copied!" por um breve período
 
                var $this = $(this);
 
                $this.addClass('copied');
 
               
 
                // Altera o texto do tooltip temporariamente
 
                $this.attr('data-tooltip-text', 'Copied!');
 
               
 
                setTimeout(function () {
 
                    $this.removeClass('copied');
 
                    $this.attr('data-tooltip-text', 'Copy');
 
                }, 1500);
 
            }
 
        } catch (err) {
 
            console.error('Erro ao copiar texto: ', err);
 
        }
 
       
 
        // Remove o elemento temporário
 
        document.body.removeChild(tempInput);
 
    });
 
});
 
 
/* Script para adicionar funcionalidade de cópia às imagens dos NPCs */
 
$(function() {
 
  // Espera o carregamento completo do conteúdo da wiki
 
  mw.hook('wikipage.content').add(function ($content) {
 
    // Identifica os links dentro dos containers de imagem
 
    $content.find('.contents-equipment .tile-top.tile-image a').each(function() {
 
      var $link = $(this);
 
      var linkHref = $link.attr('href') || '';
 
     
 
      // Extrai o ID do NPC do link (remove o # do início)
 
      var npcId = linkHref.startsWith('#') ? linkHref.substring(1) : linkHref;
 
     
 
      if (npcId) {
 
        // Adiciona um handler de clique que irá copiar o texto
 
        $link.on('mousedown', function(e) {
 
          // Texto que será copiado - usa o ID específico do NPC
 
          var textToCopy = "@warp " + npcId;
 
         
 
          // Cria um elemento temporário para copiar o texto
 
          var tempInput = document.createElement('textarea');
 
          tempInput.value = textToCopy;
 
          document.body.appendChild(tempInput);
 
          tempInput.select();
 
         
 
          try {
 
            // Executa o comando de cópia
 
            document.execCommand('copy');
 
           
 
            // Mostrar feedback visual temporário
 
            $('<div class="copy-notification" style="position:fixed;bottom:20px;right:20px;background:#4CAF50;color:white;padding:10px;border-radius:5px;z-index:9999;">Copiado: ' + textToCopy + '</div>')
 
              .appendTo('body')
 
              .delay(1500)
 
              .fadeOut(300, function() { $(this).remove(); });
 
             
 
          } catch (err) {
 
            console.error('Erro ao copiar texto: ', err);
 
          }
 
         
 
          // Remove o elemento temporário
 
          document.body.removeChild(tempInput);
 
         
 
          // Permite que o evento continue normalmente
 
          return true;
 
        });
 
      }
 
    });
 
  });
 
 
});
 
});

Latest revision as of 02:07, 6 May 2025

/* Any JavaScript here will be loaded for all users on every page load. */

$(document).ready(function() {
  // Função única para cópia de texto
  $(document).on('click', '.warp-copy', function(e) {
    e.preventDefault();
    var textToCopy = $(this).attr('data-copy');
    
    // Cria elemento temporário para cópia
    var tempInput = document.createElement('textarea');
    tempInput.value = textToCopy;
    document.body.appendChild(tempInput);
    tempInput.select();
    document.execCommand('copy');
    document.body.removeChild(tempInput);
    
    // Adiciona classe para feedback visual
    var $element = $(this);
    $element.addClass('copied');
    setTimeout(function() {
      $element.removeClass('copied');
    }, 2000);
  });

  // Adicionar funcionalidade às imagens dos NPCs
  function initImageCopy() {
    $('.tile-top.tile-image a').each(function() {
      var $link = $(this);
      if (!$link.hasClass('warp-copy')) {
        var npcId = $link.attr('href').replace('#','');
        $link.addClass('warp-copy')
             .attr('data-copy', '@warp ' + npcId)
             .css('cursor', 'pointer');
      }
    });
    
    // Aplicar tamanhos personalizados para imagens
    $('.tile-top.tile-image img').each(function() {
      var $img = $(this);
      var width = $img.data('width') || $img.attr('width');
      var height = $img.data('height') || $img.attr('height');
      
      if (width || height) {
        $img.addClass('custom-size');
        if (width) {
          $img.css('--custom-width', width + 'px');
        }
        if (height) {
          $img.css('--custom-height', height + 'px');
        }
      }
    });
  }

  // Inicializar ao carregar e em atualizações de conteúdo
  initImageCopy();
  if (typeof mw !== 'undefined' && mw.hook) {
    mw.hook('wikipage.content').add(initImageCopy);
  }

  /* Auto-expand sections when clicking anchored links */
  console.log("Inicializando script para expandir seções com links âncora");
  
  // Handle initial page load with hash
  if (window.location.hash) {
    console.log("Página carregada com hash: " + window.location.hash);
    setTimeout(function() {
      expandSectionForAnchor(window.location.hash);
    }, 300);
  }
  
  // Handle clicks on anchor links
  $(document).on('click', 'a[href^="#"]', function(event) {
    var hash = $(this).attr('href');
    console.log("Clique em link âncora: " + hash);
    event.preventDefault();
    
    if (history.pushState) {
      history.pushState(null, null, hash);
    } else {
      location.hash = hash;
    }
    
    expandSectionForAnchor(hash);
  });
  
  function expandSectionForAnchor(hash) {
    console.log("Procurando e expandindo seção para âncora: " + hash);
    var targetElement = $(hash);
    
    if (targetElement.length) {
      console.log("Elemento alvo encontrado");
      
      var collapsibleSections = targetElement.parents('.mw-collapsible.mw-collapsed');
      var directCollapsible = targetElement.closest('.mw-collapsible.mw-collapsed');
      
      if (directCollapsible.length) {
        collapsibleSections = collapsibleSections.add(directCollapsible);
      }
      
      console.log("Seções colapsáveis encontradas: " + collapsibleSections.length);
      
      if (collapsibleSections.length > 0) {
        collapsibleSections.each(function() {
          var section = $(this);
          console.log("Expandindo seção colapsável");
          
          section.removeClass('mw-collapsed');
          var toggleButton = section.find('.mw-collapsible-toggle').first();
          if (toggleButton.length) {
            console.log("Clicando no botão de expansão");
            toggleButton.click();
          }
          
          if (section.hasClass('wikitable')) {
            console.log("Expandindo tabela wikitable");
            section.find('tr:not(:first-child)').show();
          }
          
          section.find('.mw-collapsible-content').show();
        });
        
        setTimeout(function() {
          scrollToTarget(targetElement);
        }, 400);
      } else {
        scrollToTarget(targetElement);
      }
    } else {
      console.log("Elemento alvo não encontrado para hash: " + hash);
    }
  }
  
  function scrollToTarget(element) {
    console.log("Rolando até o elemento alvo");
    $('html, body').animate({
      scrollTop: element.offset().top - 100
    }, 200);
  }
  
  if (typeof mw !== 'undefined' && mw.hook) {
    mw.hook('wikipage.content').add(function() {
      console.log("Conteúdo da wiki atualizado");
      if (window.location.hash) {
        setTimeout(function() {
          expandSectionForAnchor(window.location.hash);
        }, 300);
      }
    });
  }
});