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() {
   // Função para tratar o clique em elementos copiáveis
+
   $(document).on('click', '.warp-copy', function() {
  function handleCopyClick(element) {
+
     var textToCopy = $(this).attr('data-copy');
     var textToCopy = $(element).attr('data-copy');
 
 
      
 
      
 
     var tempInput = document.createElement('textarea');
 
     var tempInput = document.createElement('textarea');
Line 13: Line 12:
 
     document.body.removeChild(tempInput);
 
     document.body.removeChild(tempInput);
 
      
 
      
     // Adiciona a classe 'copied' para mostrar o tooltip "Copied!"
+
     // Store original color
     $(element).addClass('copied');
+
     var originalColor = $(this).css('color');
    console.log("Copiado: " + textToCopy + ", Elemento: ", element);
 
 
      
 
      
     var originalColor = $(element).css('color');
+
     // Add "copied" class for tooltip feedback
     $(element).css('color', 'green');
+
     $(this).addClass('copied');
 
      
 
      
 +
    // Change color to green
 +
    $(this).css('color', 'green');
 +
   
 +
    var self = this;
 
     setTimeout(function() {
 
     setTimeout(function() {
       $(element).css('color', originalColor);
+
      // Reset color to original
       // Remove a classe 'copied' após o timeout
+
       $(self).css('color', originalColor);
       $(element).removeClass('copied');
+
       // Remove copied class
     }, 1000); // Aumentei para 1000ms para dar mais tempo para ver o feedback
+
       $(self).removeClass('copied');
  }
+
     }, 1500);
 
 
  // Handler para todos os elementos com classe warp-copy
 
  $(document).on('click', '.warp-copy', function(e) {
 
    e.preventDefault(); // Previne o comportamento padrão
 
    e.stopPropagation(); // Evita propagação do evento para elementos pais
 
    handleCopyClick(this);
 
    return false; // Impede qualquer outro comportamento padrão
 
  });
 
 
 
  // Handler específico para os títulos dos NPCs
 
  $(document).on('click', '.tile-bottom.link-button h2 .warp-copy', function(e) {
 
    e.preventDefault(); // Previne o comportamento padrão
 
    e.stopPropagation(); // Evita propagação do evento para elementos pais
 
    console.log("Clique no título NPC detectado");
 
    handleCopyClick(this);
 
    return false; // Impede qualquer outro comportamento padrão
 
 
   });
 
   });
 
});
 
});
Line 216: Line 202:
 
       initNpcCopyLinks();
 
       initNpcCopyLinks();
 
     });
 
     });
  }
 
 
 
  // Garante que o tooltip esteja visível em elementos específicos
 
  function fixTooltips() {
 
    // Força atualização dos elementos warp-copy em títulos de NPCs
 
    $('.tile-bottom.link-button h2 .warp-copy').each(function() {
 
      // Certifica-se de que o elemento tem o estilo correto
 
      $(this).attr('title', 'Click to Copy');
 
    });
 
  }
 
 
 
  // Executa quando a página carrega
 
  fixTooltips();
 
 
 
  // Também quando o conteúdo da wiki é atualizado
 
  if (typeof mw !== 'undefined' && mw.hook) {
 
    mw.hook('wikipage.content').add(fixTooltips);
 
 
   }
 
   }
 
});
 
});

Revision as of 13:00, 30 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);
    
    // 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
    if (history.pushState) {
      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
      // Primeiro os pais diretos
      var collapsibleSections = targetElement.parents('.mw-collapsible.mw-collapsed');
      
      // Depois verifica se o próprio elemento está em uma seção colapsável
      var directCollapsible = targetElement.closest('.mw-collapsible.mw-collapsed');
      if (directCollapsible.length) {
        collapsibleSections = collapsibleSections.add(directCollapsible);
      }
      
      console.log("Seções colapsáveis encontradas: " + collapsibleSections.length);
      
      // 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);
    }
  }
  
  // Função auxiliar para rolar até o elemento alvo
  function scrollToTarget(element) {
    console.log("Rolando até o elemento alvo");
    $('html, body').animate({
      scrollTop: element.offset().top - 100
    }, 200);
  }
  
  // Adicionar hook para quando o conteúdo da wiki for atualizado
  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);
      }
    });
  }
});

/* Script para adicionar funcionalidade de cópia às imagens dos NPCs */
$(function() {
  // Espera o carregamento completo do conteúdo da wiki
  function initNpcCopyLinks() {
    console.log("Inicializando links de cópia para NPCs");
    // Identifica os links dentro dos containers de imagem
    $('.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) {
        // 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
  initNpcCopyLinks();
  
  // Também inicializa quando o conteúdo da wiki é atualizado
  if (typeof mw !== 'undefined' && mw.hook) {
    mw.hook('wikipage.content').add(function() {
      initNpcCopyLinks();
    });
  }
});