Difference between revisions of "MediaWiki:Common.js"

From XilePK - Ragnarok Online Server
Jump to navigation Jump to search
Line 2: Line 2:
  
 
$(document).ready(function() {
 
$(document).ready(function() {
   $(document).on('click', '.warp-copy', function() {
+
   // Função para copiar texto e mostrar feedback
     var textToCopy = $(this).attr('data-copy');
+
  function handleCopy(element) {
 +
     var textToCopy = $(element).attr('data-copy');
 
      
 
      
 +
    // Cria elemento temporário para copiar
 
     var tempInput = document.createElement('textarea');
 
     var tempInput = document.createElement('textarea');
 
     tempInput.value = textToCopy;
 
     tempInput.value = textToCopy;
 
     document.body.appendChild(tempInput);
 
     document.body.appendChild(tempInput);
 
     tempInput.select();
 
     tempInput.select();
    document.execCommand('copy');
 
    document.body.removeChild(tempInput);
 
   
 
    // Store original color
 
    var originalColor = $(this).css('color');
 
   
 
    // Add "copied" class for tooltip feedback
 
    $(this).addClass('copied');
 
   
 
    // Change color to green
 
    $(this).css('color', 'green');
 
   
 
    var self = this;
 
    setTimeout(function() {
 
      // Reset color to original
 
      $(self).css('color', originalColor);
 
      // Remove copied class
 
      $(self).removeClass('copied');
 
    }, 1500);
 
  });
 
});
 
 
/* Auto-expand sections when clicking anchored links */
 
$(document).ready(function() {
 
  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);
 
    // Pequeno delay para garantir que o DOM esteja completamente carregado
 
    setTimeout(function() {
 
      expandSectionForAnchor(window.location.hash);
 
    }, 300);
 
  }
 
 
 
  // Handle clicks on anchor links within the page
 
  $(document).on('click', 'a[href^="#"]', function(event) {
 
    var hash = $(this).attr('href');
 
    console.log("Clique em link âncora: " + hash);
 
    // Previne o comportamento padrão para tratar manualmente
 
    event.preventDefault();
 
 
      
 
      
     // Atualiza a URL sem recarregar a página
+
     try {
    if (history.pushState) {
+
       document.execCommand('copy');
      history.pushState(null, null, hash);
 
    } else {
 
      location.hash = hash;
 
    }
 
   
 
    expandSectionForAnchor(hash);
 
  });
 
 
 
  // Function to expand section containing an anchor
 
  function expandSectionForAnchor(hash) {
 
    console.log("Procurando e expandindo seção para âncora: " + hash);
 
    // Try to find the anchor element
 
    var targetElement = $(hash);
 
   
 
    if (targetElement.length) {
 
       console.log("Elemento alvo encontrado");
 
 
        
 
        
       // Encontrar todas as seções colapsáveis que contêm o elemento
+
       // Adiciona classe de feedback
       // Primeiro os pais diretos
+
       $(element).addClass('copied');
      var collapsibleSections = targetElement.parents('.mw-collapsible.mw-collapsed');
 
 
        
 
        
       // Depois verifica se o próprio elemento está em uma seção colapsável
+
       // Remove feedback após 1.5 segundos
       var directCollapsible = targetElement.closest('.mw-collapsible.mw-collapsed');
+
       setTimeout(function() {
      if (directCollapsible.length) {
+
         $(element).removeClass('copied');
         collapsibleSections = collapsibleSections.add(directCollapsible);
+
       }, 1500);
       }
 
 
        
 
        
      console.log("Seções colapsáveis encontradas: " + collapsibleSections.length);
+
    } catch (err) {
     
+
      console.error('Erro ao copiar:', err);
      // Expandir cada seção encontrada
 
      if (collapsibleSections.length > 0) {
 
        collapsibleSections.each(function() {
 
          var section = $(this);
 
          console.log("Expandindo seção colapsável");
 
         
 
          // Remover a classe collapsed
 
          section.removeClass('mw-collapsed');
 
         
 
          // Tentar clicar no botão de expansão
 
          var toggleButton = section.find('.mw-collapsible-toggle').first();
 
          if (toggleButton.length) {
 
            console.log("Clicando no botão de expansão");
 
            toggleButton.click();
 
          }
 
         
 
          // Para tabelas, garantir que as linhas sejam mostradas
 
          if (section.hasClass('wikitable')) {
 
            console.log("Expandindo tabela wikitable");
 
            section.find('tr:not(:first-child)').show();
 
          }
 
         
 
          // Forçar exibição do conteúdo
 
          section.find('.mw-collapsible-content').show();
 
        });
 
       
 
        // Aguardar a expansão antes de rolar
 
        setTimeout(function() {
 
          scrollToTarget(targetElement);
 
        }, 400);
 
      } else {
 
        // Se não houver seções colapsáveis, apenas role até o elemento
 
        scrollToTarget(targetElement);
 
      }
 
    } else {
 
      console.log("Elemento alvo não encontrado para hash: " + hash);
 
 
     }
 
     }
 +
   
 +
    document.body.removeChild(tempInput);
 
   }
 
   }
    
+
 
   // Função auxiliar para rolar até o elemento alvo
+
  // Click nos elementos .warp-copy
   function scrollToTarget(element) {
+
  $(document).on('click', '.warp-copy', function() {
     console.log("Rolando até o elemento alvo");
+
    handleCopy(this);
    $('html, body').animate({
+
   });
       scrollTop: element.offset().top - 100
+
 
     }, 200);
+
   // Click nas imagens dos NPCs
 +
   function initNpcCopy() {
 +
     $('.contents-equipment .tile-top.tile-image a').off('click.npccopy').on('click.npccopy', function(e) {
 +
      e.preventDefault();
 +
      var npcId = $(this).attr('href').replace('#','');
 +
       handleCopy($(this).closest('.contents-equipment').find('.warp-copy')[0]);
 +
     });
 
   }
 
   }
    
+
 
   // Adicionar hook para quando o conteúdo da wiki for atualizado
+
   // Inicializa quando o documento está pronto
 +
  initNpcCopy();
 +
 
 +
   // Reinicia quando novo conteúdo é carregado
 
   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");
+
       initNpcCopy();
      if (window.location.hash) {
 
        setTimeout(function() {
 
          expandSectionForAnchor(window.location.hash);
 
        }, 300);
 
      }
 
 
     });
 
     });
 
   }
 
   }
});
 
  
/* Script para adicionar funcionalidade de cópia às imagens dos NPCs */
+
   // Auto-expandir seções com anchor links
$(function() {
+
   function expandSectionForAnchor(hash) {
   // Espera o carregamento completo do conteúdo da wiki
+
     var targetElement = $(hash);
   function initNpcCopyLinks() {
+
     if (targetElement.length) {
     console.log("Inicializando links de cópia para NPCs");
+
       targetElement.parents('.mw-collapsible.mw-collapsed').removeClass('mw-collapsed')
     // Identifica os links dentro dos containers de imagem
+
         .find('.mw-collapsible-content').show();
    $('.contents-equipment .tile-top.tile-image a').each(function() {
+
      setTimeout(function() {
       var $link = $(this);
+
        $('html, body').animate({ scrollTop: targetElement.offset().top - 100 }, 200);
      var linkHref = $link.attr('href') || '';
+
      }, 400);
     
+
     }
      // Extrai o ID do NPC do link (remove o # do início)
 
      var npcId = linkHref.startsWith('#') ? linkHref.substring(1) : linkHref;
 
     
 
      if (npcId) {
 
        // Remove handlers anteriores para evitar duplicação
 
        $link.off('mousedown.npccopy');
 
       
 
        // Adiciona um handler de clique que irá copiar o texto
 
         $link.on('mousedown.npccopy', 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;
 
        });
 
      }
 
     });
 
 
   }
 
   }
 
+
 
   // Inicializa na carga da página
+
   // Trata hash na URL inicial
  initNpcCopyLinks();
+
   if (window.location.hash) {
 
+
     setTimeout(function() { expandSectionForAnchor(window.location.hash); }, 300);
  // Também inicializa quando o conteúdo da wiki é atualizado
 
   if (typeof mw !== 'undefined' && mw.hook) {
 
     mw.hook('wikipage.content').add(function() {
 
      initNpcCopyLinks();
 
    });
 
 
   }
 
   }
 +
 +
  // Trata clicks em links âncora
 +
  $(document).on('click', 'a[href^="#"]', function(e) {
 +
    e.preventDefault();
 +
    var hash = $(this).attr('href');
 +
    history.pushState(null, null, hash);
 +
    expandSectionForAnchor(hash);
 +
  });
 
});
 
});

Revision as of 13:07, 30 April 2025

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

$(document).ready(function() {
  // Função para copiar texto e mostrar feedback
  function handleCopy(element) {
    var textToCopy = $(element).attr('data-copy');
    
    // Cria elemento temporário para copiar
    var tempInput = document.createElement('textarea');
    tempInput.value = textToCopy;
    document.body.appendChild(tempInput);
    tempInput.select();
    
    try {
      document.execCommand('copy');
      
      // Adiciona classe de feedback
      $(element).addClass('copied');
      
      // Remove feedback após 1.5 segundos
      setTimeout(function() {
        $(element).removeClass('copied');
      }, 1500);
      
    } catch (err) {
      console.error('Erro ao copiar:', err);
    }
    
    document.body.removeChild(tempInput);
  }

  // Click nos elementos .warp-copy
  $(document).on('click', '.warp-copy', function() {
    handleCopy(this);
  });

  // Click nas imagens dos NPCs
  function initNpcCopy() {
    $('.contents-equipment .tile-top.tile-image a').off('click.npccopy').on('click.npccopy', function(e) {
      e.preventDefault();
      var npcId = $(this).attr('href').replace('#','');
      handleCopy($(this).closest('.contents-equipment').find('.warp-copy')[0]);
    });
  }

  // Inicializa quando o documento está pronto
  initNpcCopy();

  // Reinicia quando novo conteúdo é carregado
  if (typeof mw !== 'undefined' && mw.hook) {
    mw.hook('wikipage.content').add(function() {
      initNpcCopy();
    });
  }

  // Auto-expandir seções com anchor links
  function expandSectionForAnchor(hash) {
    var targetElement = $(hash);
    if (targetElement.length) {
      targetElement.parents('.mw-collapsible.mw-collapsed').removeClass('mw-collapsed')
        .find('.mw-collapsible-content').show();
      setTimeout(function() {
        $('html, body').animate({ scrollTop: targetElement.offset().top - 100 }, 200);
      }, 400);
    }
  }

  // Trata hash na URL inicial
  if (window.location.hash) {
    setTimeout(function() { expandSectionForAnchor(window.location.hash); }, 300);
  }

  // Trata clicks em links âncora
  $(document).on('click', 'a[href^="#"]', function(e) {
    e.preventDefault();
    var hash = $(this).attr('href');
    history.pushState(null, null, hash);
    expandSectionForAnchor(hash);
  });
});