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() {
+
$(document).ready(function() {
   // Função principal para executar quando a página terminar de carregar
+
   // Handle initial page load with hash
   function initializeAnchorExpansion() {
+
   if (window.location.hash) {
    // Se existir um hash na URL quando a página carrega
+
    expandSectionForAnchor(window.location.hash);
    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
+
   // Handle clicks on anchor links within the page
 +
  $(document).on('click', 'a[href^="#"]', function(event) {
 +
    var hash = $(this).attr('href');
 +
    expandSectionForAnchor(hash);
 +
  });
 +
 
 +
  // Function to expand section containing an anchor
 
   function expandSectionForAnchor(hash) {
 
   function expandSectionForAnchor(hash) {
     // Remover qualquer caractere # do início do hash se existir
+
     // Try to find the anchor element
    if (hash.startsWith('#')) {
+
     var targetElement = $(hash);
      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) {
 
     if (targetElement.length) {
      console.log("Elemento encontrado!");
+
       // Find the closest collapsible section
     
+
       var collapsibleSection = targetElement.closest('.mw-collapsible.mw-collapsed');
       // 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 the target is inside a collapsed section, expand it
       if (collapsibleSections.length > 0) {
+
       if (collapsibleSection.length) {
         // Expandir cada seção de fora para dentro
+
         // Click the toggle button to expand
         collapsibleSections.each(function() {
+
         collapsibleSection.find('.mw-collapsible-toggle').first().click();
          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
+
         // Scroll to the element after a short delay to allow expansion
         var directCollapsible = targetElement.closest('.mw-collapsible.mw-collapsed');
+
         setTimeout(function() {
        if (directCollapsible.length) {
+
           $('html, body').animate({
           console.log("Expandindo o contêiner direto");
+
             scrollTop: targetElement.offset().top - 100
          directCollapsible.removeClass('mw-collapsed');
+
           }, 200);
          var $toggle = directCollapsible.find('.mw-collapsible-toggle').first();
+
         }, 300);
          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);
 
      }
 
    });
 
  }
 
});
 
 
 
/* Script aprimorado para funcionalidade de cópia */
 
mw.hook('wikipage.content').add(function ($content) {
 
    // Remover manipuladores de eventos anteriores para evitar duplicação
 
    $content.find('.warp-copy').off('click');
 
   
 
    // Adiciona funcionalidade aos elementos com a classe warp-copy
 
    $content.find('.warp-copy').on('click', function (e) {
 
        e.preventDefault(); // Previne navegação se estiver dentro de um link
 
       
 
        // Pega o texto do atributo data-copy ou usa o texto do elemento
 
        var textToCopy = $(this).attr('data-copy') || $(this).text();
 
       
 
        // 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
 
            if (successful) {
 
                var $this = $(this);
 
                $this.addClass('copied');
 
               
 
                // Mostra o feedback por 1.5 segundos
 
                setTimeout(function () {
 
                    $this.removeClass('copied');
 
                }, 1500);
 
               
 
                // Opcional: feedback visual adicional
 
                $('<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);
 
       
 
        return false; // Impede comportamento padrão
 
    });
 
});
 
 
/* 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;
 
        });
 
      }
 
    });
 
  });
 
});
 
 
 
 
 
// Função para inicializar tooltips nos elementos .warp-copy
 
function initializeWarpCopyTooltips() {
 
    console.log("Inicializando tooltips para elementos .warp-copy");
 
 
    // Selecionar todos os elementos com classe .warp-copy
 
    var copyElements = document.querySelectorAll('.warp-copy');
 
   
 
    copyElements.forEach(function(element) {
 
        // Garantir que o elemento tenha os atributos necessários para o tooltip
 
        if (!element.getAttribute('title')) {
 
            element.setAttribute('title', 'Copy');
 
        }
 
       
 
        // Remover handlers anteriores para evitar duplicação
 
        element.removeEventListener('click', handleCopyClick);
 
        element.addEventListener('click', handleCopyClick);
 
    });
 
}
 
 
// Função para lidar com cliques nos elementos copiáveis
 
function handleCopyClick(event) {
 
    event.preventDefault();
 
   
 
    var element = event.currentTarget;
 
    var textToCopy = element.getAttribute('data-copy') || element.textContent;
 
   
 
    // Criar elemento temporário para copiar texto
 
    var tempInput = document.createElement('textarea');
 
    tempInput.value = textToCopy;
 
    document.body.appendChild(tempInput);
 
    tempInput.select();
 
   
 
    try {
 
        // Executar o comando de cópia
 
        var successful = document.execCommand('copy');
 
       
 
        if (successful) {
 
            // Adicionar classe para efeito visual
 
            element.classList.add('copied');
 
           
 
            // Restaurar após 1.5 segundos
 
            setTimeout(function() {
 
                element.classList.remove('copied');
 
            }, 1500);
 
           
 
            // Feedback visual opcional
 
            var notification = document.createElement('div');
 
            notification.className = 'copy-notification';
 
            notification.style.cssText = 'position:fixed;bottom:20px;right:20px;background:#4CAF50;color:white;padding:10px;border-radius:5px;z-index:9999;';
 
            notification.textContent = 'Copiado: ' + textToCopy;
 
            document.body.appendChild(notification);
 
           
 
            setTimeout(function() {
 
                if (notification.parentNode) {
 
                    notification.parentNode.removeChild(notification);
 
                }
 
            }, 1500);
 
        }
 
    } catch (err) {
 
        console.error('Erro ao copiar texto:', err);
 
    }
 
   
 
    // Remover o elemento temporário
 
    document.body.removeChild(tempInput);
 
    return false;
 
}
 
 
// Inicializar quando o DOM estiver pronto
 
$(document).ready(function() {
 
    initializeWarpCopyTooltips();
 
   
 
    // Também inicializar quando o conteúdo da wiki for carregado/atualizado
 
    if (typeof mw !== 'undefined' && mw.hook) {
 
        mw.hook('wikipage.content').add(function() {
 
            console.log("Conteúdo da wiki atualizado, reinicializando tooltips");
 
            initializeWarpCopyTooltips();
 
        });
 
    }
 
 
});
 
});

Revision as of 17:35, 29 April 2025

/* 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 */
$(document).ready(function() {
  // Handle initial page load with hash
  if (window.location.hash) {
    expandSectionForAnchor(window.location.hash);
  }
  
  // Handle clicks on anchor links within the page
  $(document).on('click', 'a[href^="#"]', function(event) {
    var hash = $(this).attr('href');
    expandSectionForAnchor(hash);
  });
  
  // Function to expand section containing an anchor
  function expandSectionForAnchor(hash) {
    // Try to find the anchor element
    var targetElement = $(hash);
    if (targetElement.length) {
      // Find the closest collapsible section
      var collapsibleSection = targetElement.closest('.mw-collapsible.mw-collapsed');
      
      // If the target is inside a collapsed section, expand it
      if (collapsibleSection.length) {
        // Click the toggle button to expand
        collapsibleSection.find('.mw-collapsible-toggle').first().click();
        
        // Scroll to the element after a short delay to allow expansion
        setTimeout(function() {
          $('html, body').animate({
            scrollTop: targetElement.offset().top - 100
          }, 200);
        }, 300);
      }
    }
  }
});