Difference between revisions of "MediaWiki:Common.js"

From XilePK - Ragnarok Online Server
Jump to navigation Jump to search
Line 95: Line 95:
 
});
 
});
  
/* JavaScript melhorado para funcionalidade de cópia */
 
$(document).ready(function() {
 
    // Adicionar CSS personalizado inline para forçar os tooltips
 
    $('<style>')
 
        .text(`
 
            .warp-copy:hover::after,
 
            .warp-copy:hover::before {
 
                opacity: 1 !important;
 
                visibility: visible !important;
 
                display: block !important;
 
            }
 
            .warp-copy.copied::after {
 
                content: "Copiado!" !important;
 
                background-color: #4CAF50 !important;
 
                display: block !important;
 
            }
 
        `)
 
        .appendTo('head');
 
});
 
  
 +
/* JavaScript para funcionalidade de cópia */
 
mw.hook('wikipage.content').add(function ($content) {
 
mw.hook('wikipage.content').add(function ($content) {
     // Função para inicializar todos os elementos .warp-copy
+
     // Adiciona funcionalidade aos elementos com a classe warp-copy
     function initWarpCopy() {
+
     $content.find('.warp-copy').on('click', function () {
         console.log("Inicializando elementos .warp-copy");
+
         var textToCopy = $(this).attr('data-copy');
 
          
 
          
         // Remove manipuladores de eventos anteriores para evitar duplicações
+
         // Cria um elemento temporário para copiar o texto
        $content.find('.warp-copy').off('click');
 
       
 
        // Adiciona o manipulador de clique
 
        $content.find('.warp-copy').on('click', function (event) {
 
            event.preventDefault();
 
            event.stopPropagation();
 
           
 
            var $this = $(this);
 
            var textToCopy = $this.attr('data-copy');
 
           
 
            if (!textToCopy) {
 
                console.warn("Elemento .warp-copy sem atributo data-copy encontrado");
 
                return;
 
            }
 
           
 
            console.log("Copiando texto: " + textToCopy);
 
           
 
            // Usa a API Clipboard moderna quando disponível
 
            if (navigator.clipboard && navigator.clipboard.writeText) {
 
                navigator.clipboard.writeText(textToCopy)
 
                    .then(function() {
 
                        console.log('Texto copiado com sucesso usando Clipboard API');
 
                        showCopiedFeedback($this);
 
                    })
 
                    .catch(function(err) {
 
                        console.error('Falha ao copiar texto: ', err);
 
                        // Tenta o método de fallback
 
                        fallbackCopyText(textToCopy, $this);
 
                    });
 
            } else {
 
                // Método de fallback para navegadores que não suportam a API Clipboard
 
                fallbackCopyText(textToCopy, $this);
 
            }
 
        });
 
    }
 
   
 
    // Função de fallback para copiar texto
 
    function fallbackCopyText(text, $element) {
 
        // Cria um elemento de texto temporário
 
 
         var tempInput = document.createElement('textarea');
 
         var tempInput = document.createElement('textarea');
         tempInput.value = text;
+
         tempInput.value = textToCopy;
        tempInput.style.position = 'fixed';
 
        tempInput.style.opacity = '0';
 
 
         document.body.appendChild(tempInput);
 
         document.body.appendChild(tempInput);
       
 
        // Seleciona e copia
 
 
         tempInput.select();
 
         tempInput.select();
        tempInput.setSelectionRange(0, 99999); // Para dispositivos móveis
 
 
          
 
          
 
         try {
 
         try {
 +
            // Executa o comando de cópia
 
             var successful = document.execCommand('copy');
 
             var successful = document.execCommand('copy');
 +
           
 +
            // Feedback visual temporário ao usuário
 +
            var originalText = $(this).text();
 
             if (successful) {
 
             if (successful) {
                 console.log('Texto copiado com sucesso usando execCommand');
+
                 // Altera o texto do tooltip para "Copied!" por um breve período
                 showCopiedFeedback($element);
+
                var $this = $(this);
            } else {
+
                $this.addClass('copied');
                console.error('Falha ao copiar texto com execCommand');
+
                  
 +
                // 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) {
 
         } catch (err) {
Line 184: Line 133:
 
         // Remove o elemento temporário
 
         // Remove o elemento temporário
 
         document.body.removeChild(tempInput);
 
         document.body.removeChild(tempInput);
     }
+
     });
   
+
});
    // Função para mostrar feedback visual de cópia
+
 
    function showCopiedFeedback($element) {
+
/* Script para adicionar funcionalidade de cópia às imagens dos NPCs */
        // Adiciona classe para feedback visual
+
$(function() {
        $element.addClass('copied');
+
  // Espera o carregamento completo do conteúdo da wiki
       
+
  mw.hook('wikipage.content').add(function ($content) {
        // Remove a classe após um breve período
+
     // Identifica os links dentro dos containers de imagem
        setTimeout(function() {
+
     $content.find('.contents-equipment .tile-top.tile-image a').each(function() {
            $element.removeClass('copied');
+
      var $link = $(this);
        }, 1500);
+
      var linkHref = $link.attr('href') || '';
       
+
     
        // Opcional: mostrar um popup de notificação
+
      // Extrai o ID do NPC do link (remove o # do início)
        $('<div class="copy-notification" style="position:fixed;bottom:20px;right:20px;background:#4CAF50;color:white;padding:10px;border-radius:5px;z-index:9999;">Copiado: ' + $element.attr('data-copy') + '</div>')
+
      var npcId = linkHref.startsWith('#') ? linkHref.substring(1) : linkHref;
            .appendTo('body')
+
     
            .delay(1500)
+
      if (npcId) {
            .fadeOut(300, function() { $(this).remove(); });
+
        // 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
     // Script para imagens dos NPCs
+
          var textToCopy = "@warp " + npcId;
     function initNPCImageCopy() {
+
         
        $content.find('.contents-equipment .tile-top.tile-image a').each(function() {
+
          // Cria um elemento temporário para copiar o texto
            var $link = $(this);
+
          var tempInput = document.createElement('textarea');
            var linkHref = $link.attr('href') || '';
+
          tempInput.value = textToCopy;
 +
          document.body.appendChild(tempInput);
 +
          tempInput.select();
 +
         
 +
          try {
 +
            // Executa o comando de cópia
 +
            document.execCommand('copy');
 
              
 
              
             // Extrai o ID do NPC do link
+
             // Mostrar feedback visual temporário
             var npcId = linkHref.startsWith('#') ? linkHref.substring(1) : linkHref;
+
             $('<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')
            if (npcId) {
+
              .delay(1500)
                $link.off('mousedown').on('mousedown', function(e) {
+
              .fadeOut(300, function() { $(this).remove(); });
                    // Texto a ser copiado
+
             
                    var textToCopy = "@warp " + npcId;
+
          } catch (err) {
                   
+
            console.error('Erro ao copiar texto: ', err);
                    // Tenta usar a API Clipboard moderna
+
          }
                    if (navigator.clipboard && navigator.clipboard.writeText) {
+
         
                        navigator.clipboard.writeText(textToCopy)
+
          // Remove o elemento temporário
                            .then(function() {
+
          document.body.removeChild(tempInput);
                                console.log('Comando @warp copiado com sucesso');
+
         
                                showCopiedNotification(textToCopy);
+
          // Permite que o evento continue normalmente
                            })
+
          return true;
                            .catch(function(err) {
 
                                console.error('Falha ao copiar comando @warp: ', err);
 
                                // Usa o método de fallback
 
                                fallbackCopyText(textToCopy, $link);
 
                            });
 
                    } else {
 
                        // Método de fallback
 
                        fallbackCopyNPCCommand(textToCopy);
 
                    }
 
                   
 
                    // Permite que o evento continue
 
                    return true;
 
                });
 
            }
 
 
         });
 
         });
    }
+
      }
   
 
    // Função de fallback para copiar comando de NPC
 
    function fallbackCopyNPCCommand(text) {
 
        var tempInput = document.createElement('textarea');
 
        tempInput.value = text;
 
        tempInput.style.position = 'fixed';
 
        tempInput.style.opacity = '0';
 
        document.body.appendChild(tempInput);
 
       
 
        tempInput.select();
 
        tempInput.setSelectionRange(0, 99999); // Para dispositivos móveis
 
       
 
        try {
 
            document.execCommand('copy');
 
            showCopiedNotification(text);
 
        } catch (err) {
 
            console.error('Erro ao copiar comando @warp: ', err);
 
        }
 
       
 
        document.body.removeChild(tempInput);
 
    }
 
   
 
    // Função para mostrar notificação de cópia
 
    function showCopiedNotification(text) {
 
        $('<div class="copy-notification" style="position:fixed;bottom:20px;right:20px;background:#4CAF50;color:white;padding:10px;border-radius:5px;z-index:9999;">Copiado: ' + text + '</div>')
 
            .appendTo('body')
 
            .delay(1500)
 
            .fadeOut(300, function() { $(this).remove(); });
 
    }
 
   
 
    // Inicializa todas as funções
 
    initWarpCopy();
 
    initNPCImageCopy();
 
   
 
    // Forçar a atualização dos tooltips (hack)
 
    setTimeout(function() {
 
        $content.find('.warp-copy').each(function() {
 
            var $this = $(this);
 
            $this.attr('title', 'Clique para Copiar');
 
        });
 
    }, 500);
 
   
 
    // Observador para alterações no DOM
 
    var observer = new MutationObserver(function(mutations) {
 
        var needsReinit = false;
 
       
 
        mutations.forEach(function(mutation) {
 
            if (mutation.addedNodes && mutation.addedNodes.length > 0) {
 
                needsReinit = true;
 
            }
 
        });
 
       
 
        if (needsReinit) {
 
            initWarpCopy();
 
            initNPCImageCopy();
 
        }
 
 
     });
 
     });
   
+
  });
    // Configura o observador
 
    observer.observe($content[0], { childList: true, subtree: true });
 
 
});
 
});

Revision as of 16:12, 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);
      }
    });
  }
});


/* 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;
        });
      }
    });
  });
});