Difference between revisions of "MediaWiki:Common.js"

From XilePK - Ragnarok Online Server
Jump to navigation Jump to search
 
(21 intermediate revisions by the same user not shown)
Line 1: Line 1:
/* MediaWiki common.js - Versão otimizada */
+
/* Any JavaScript here will be loaded for all users on every page load. */
  
/* ======= Parte 1: Auto-expansão de seções ao clicar em links âncora ======= */
+
$(document).ready(function() {
$(function() {
+
   // Função única para cópia de texto
  console.log("Inicializando script de expansão automática para links âncora");
+
   $(document).on('click', '.warp-copy', function(e) {
 
+
     e.preventDefault();
   // Função que expande as seções colapsáveis baseadas no hash da URL
+
     var textToCopy = $(this).attr('data-copy');
   function expandSectionForAnchor(hash, scrollToElement = true) {
 
     // Remover o # do início se existir
 
     if (hash.startsWith('#')) {
 
      hash = hash.substring(1);
 
    }
 
 
      
 
      
     console.log("Procurando elemento com ID: " + 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);
 
      
 
      
     if (!hash) return; // Sair se não houver hash
+
     // 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');
 +
      }
 +
    });
 
      
 
      
     // Encontra o elemento alvo
+
     // Aplicar tamanhos personalizados para imagens
     var $targetElement = $('#' + hash);
+
     $('.tile-top.tile-image img').each(function() {
   
+
      var $img = $(this);
    if ($targetElement.length) {
+
      var width = $img.data('width') || $img.attr('width');
       console.log("Elemento encontrado com ID: " + hash);
+
       var height = $img.data('height') || $img.attr('height');
 
        
 
        
      // Encontre todas as seções colapsáveis que contêm o elemento
+
       if (width || height) {
      var $collapsibleAncestors = $targetElement.parents('.mw-collapsible.mw-collapsed');
+
         $img.addClass('custom-size');
     
+
        if (width) {
      // Também pegar tabelas wikitable colapsáveis
+
           $img.css('--custom-width', width + 'px');
      var $wikitableAncestors = $targetElement.parents('.wikitable.mw-collapsible.mw-collapsed');
+
         }
     
+
         if (height) {
      // Unir os conjuntos de elementos
+
           $img.css('--custom-height', height + 'px');
      $collapsibleAncestors = $collapsibleAncestors.add($wikitableAncestors);
 
     
 
      console.log("Seções colapsáveis encontradas: " + $collapsibleAncestors.length);
 
     
 
      // Se houver seções colapsáveis contendo o elemento
 
       if ($collapsibleAncestors.length > 0) {
 
         console.log("Expandindo seções colapsáveis...");
 
       
 
        // Expandir cada seção de fora para dentro
 
        $collapsibleAncestors.each(function() {
 
          var $section = $(this);
 
         
 
          // Remover classe de colapsado
 
          $section.removeClass('mw-collapsed');
 
         
 
          // Tentar diferentes métodos para expandir:
 
         
 
          // 1. Método nativo do MediaWiki
 
          if (typeof mw !== 'undefined' && typeof mw.loader !== 'undefined') {
 
            mw.loader.using('jquery.makeCollapsible', function() {
 
              $section.makeCollapsible();
 
            });
 
          }
 
            
 
          // 2. Ou usar os togglers existentes
 
          var $toggle = $section.find('.mw-collapsible-toggle').first();
 
          if ($toggle.length) {
 
            console.log("Clicando no botão toggle");
 
            $toggle.trigger('click');
 
          }
 
         
 
          // 3. Ou forçar a exibição do conteúdo diretamente
 
          $section.find('.mw-collapsible-content').show();
 
         
 
          // 4. Para tabelas wikitable especificamente
 
          if ($section.hasClass('wikitable')) {
 
            $section.find('tr:not(:first-child)').show();
 
          }
 
         
 
          // 5. Remover quaisquer estilos que possam estar escondendo o conteúdo
 
          $section.find('.mw-collapsible-content, tr:not(:first-child)').css({
 
            'display': 'table-row',
 
            'visibility': 'visible',
 
            'height': 'auto',
 
            'opacity': '1'
 
          });
 
         });
 
       
 
        // 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');
 
         
 
          // Se for uma tabela, mostrar todas as linhas
 
          if ($directCollapsible.hasClass('wikitable')) {
 
            $directCollapsible.find('tr:not(:first-child)').show();
 
          } else {
 
            $directCollapsible.find('.mw-collapsible-content').show();
 
          }
 
 
         }
 
         }
       
 
        // Dar um tempo para as animações terminarem antes de rolar
 
        setTimeout(function() {
 
          if (scrollToElement) {
 
            console.log("Rolando até o elemento");
 
            $('html, body').animate({
 
              scrollTop: $targetElement.offset().top - 100
 
            }, 200);
 
          }
 
        }, 500); // Aumentado para 500ms para dar mais tempo para expansão
 
      } else if (scrollToElement) {
 
        // Se não houver seções colapsáveis, apenas role até o elemento
 
        console.log("Rolando até o elemento sem expansão necessária");
 
        $('html, body').animate({
 
          scrollTop: $targetElement.offset().top - 100
 
        }, 200);
 
 
       }
 
       }
     } else {
+
     });
      console.log("Elemento com ID '" + hash + "' não encontrado");
+
  }
    }
+
 
 +
  // 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");
 
    
 
    
   // Verificar se há hash na URL quando a página carrega
+
   // Handle initial page load with hash
 
   if (window.location.hash) {
 
   if (window.location.hash) {
 
     console.log("Página carregada com hash: " + window.location.hash);
 
     console.log("Página carregada com hash: " + window.location.hash);
    // Usar setTimeout para garantir que o DOM esteja completamente carregado
 
 
     setTimeout(function() {
 
     setTimeout(function() {
 
       expandSectionForAnchor(window.location.hash);
 
       expandSectionForAnchor(window.location.hash);
     }, 500); // Aumentado para 500ms para garantir carregamento completo
+
     }, 300);
 
   }
 
   }
 
    
 
    
   // Lidar com cliques em links âncora dentro da página
+
   // Handle clicks on anchor links
 
   $(document).on('click', 'a[href^="#"]', function(event) {
 
   $(document).on('click', 'a[href^="#"]', function(event) {
 
     var hash = $(this).attr('href');
 
     var hash = $(this).attr('href');
     console.log("Clique em link interno: " + hash);
+
     console.log("Clique em link âncora: " + hash);
 +
    event.preventDefault();
 
      
 
      
    // Se já estamos na mesma página, expandir seções e prevenir comportamento padrão
+
     if (history.pushState) {
     if (hash && hash.startsWith('#')) {
+
      history.pushState(null, null, hash);
      event.preventDefault();
+
    } else {
      expandSectionForAnchor(hash);
+
      location.hash = hash;
     
 
      // Atualizar a URL sem recarregar a página
 
      if (history.pushState) {
 
        history.pushState(null, null, hash);
 
      } else {
 
        location.hash = hash;
 
      }
 
 
     }
 
     }
 +
   
 +
    expandSectionForAnchor(hash);
 
   });
 
   });
 
    
 
    
   // Adicionar um hook para quando o conteúdo da página for modificado
+
   function expandSectionForAnchor(hash) {
  if (typeof mw !== 'undefined' && mw.hook) {
+
     console.log("Procurando e expandindo seção para âncora: " + hash);
     mw.hook('wikipage.content').add(function($content) {
+
     var targetElement = $(hash);
      console.log("Conteúdo da Wiki atualizado, reinicializando manipuladores");
 
     
 
      // Se houver hash na URL, expandir as seções relevantes
 
      if (window.location.hash) {
 
        setTimeout(function() {
 
          expandSectionForAnchor(window.location.hash);
 
        }, 300);
 
      }
 
     });
 
  }
 
});
 
 
 
/* ======= Parte 2: Funcionalidade de cópia ======= */
 
$(function() {
 
  // Função principal para inicializar funcionalidade de cópia
 
  function initializeCopyFunctionality() {
 
    console.log("Inicializando funcionalidade de cópia");
 
 
      
 
      
     // Remover manipuladores de eventos anteriores para evitar duplicação
+
     if (targetElement.length) {
    $('.warp-copy').off('click');
+
       console.log("Elemento alvo encontrado");
   
 
    // Adiciona funcionalidade aos elementos com a classe warp-copy
 
    $('.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 collapsibleSections = targetElement.parents('.mw-collapsible.mw-collapsed');
       var textToCopy = $(this).attr('data-copy') || $(this).text();
+
       var directCollapsible = targetElement.closest('.mw-collapsible.mw-collapsed');
 
        
 
        
       copyTextToClipboard(textToCopy, $(this));
+
       if (directCollapsible.length) {
 +
        collapsibleSections = collapsibleSections.add(directCollapsible);
 +
      }
 
        
 
        
       return false; // Impede comportamento padrão
+
       console.log("Seções colapsáveis encontradas: " + collapsibleSections.length);
    });
 
   
 
    // Identifica os links dentro dos containers de imagem de NPCs
 
    $('.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)
+
       if (collapsibleSections.length > 0) {
      var npcId = linkHref.startsWith('#') ? linkHref.substring(1) : linkHref;
+
        collapsibleSections.each(function() {
     
+
          var section = $(this);
      if (npcId) {
+
          console.log("Expandindo seção colapsável");
        // Remove manipuladores existentes para evitar duplicação
+
         
        $link.off('mousedown.warpcopy');
+
          section.removeClass('mw-collapsed');
       
+
          var toggleButton = section.find('.mw-collapsible-toggle').first();
        // Adiciona um handler de clique que irá copiar o texto
+
           if (toggleButton.length) {
        $link.on('mousedown.warpcopy', function(e) {
+
            console.log("Clicando no botão de expansão");
           // Texto que será copiado - usa o ID específico do NPC
+
            toggleButton.click();
          var textToCopy = "@warp " + npcId;
+
          }
 
            
 
            
           copyTextToClipboard(textToCopy);
+
           if (section.hasClass('wikitable')) {
 +
            console.log("Expandindo tabela wikitable");
 +
            section.find('tr:not(:first-child)').show();
 +
          }
 
            
 
            
           // Permite que o evento continue normalmente
+
           section.find('.mw-collapsible-content').show();
          return true;
 
 
         });
 
         });
      }
 
    });
 
  }
 
 
 
  // Função auxiliar para copiar texto para a área de transferência
 
  function copyTextToClipboard(text, $element) {
 
    // Cria um elemento temporário para copiar o texto
 
    var tempInput = document.createElement('textarea');
 
    tempInput.value = text;
 
    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) {
 
        if ($element) {
 
          $element.addClass('copied');
 
         
 
          // Mostra o feedback por 1.5 segundos
 
          setTimeout(function() {
 
            $element.removeClass('copied');
 
          }, 1500);
 
        }
 
 
          
 
          
         // Feedback visual adicional
+
         setTimeout(function() {
        $('<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>')
+
           scrollToTarget(targetElement);
          .appendTo('body')
+
        }, 400);
           .delay(1500)
+
      } else {
          .fadeOut(300, function() { $(this).remove(); });
+
        scrollToTarget(targetElement);
 
       }
 
       }
     } catch (err) {
+
     } else {
       console.error('Erro ao copiar texto: ', err);
+
       console.log("Elemento alvo não encontrado para hash: " + hash);
 
     }
 
     }
   
 
    // Remove o elemento temporário
 
    document.body.removeChild(tempInput);
 
 
   }
 
   }
 
    
 
    
   // Inicializar quando o DOM estiver pronto
+
   function scrollToTarget(element) {
  initializeCopyFunctionality();
+
    console.log("Rolando até o elemento alvo");
 +
    $('html, body').animate({
 +
      scrollTop: element.offset().top - 100
 +
    }, 200);
 +
  }
 
    
 
    
  // Também inicializar quando o conteúdo da wiki for carregado/atualizado
 
 
   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 funcionalidade de cópia");
+
       console.log("Conteúdo da wiki atualizado");
       initializeCopyFunctionality();
+
       if (window.location.hash) {
    });
+
        setTimeout(function() {
  }
+
          expandSectionForAnchor(window.location.hash);
});
+
         }, 300);
 
 
/* ======= Parte 3: Tooltips para elementos copiáveis ======= */
 
$(function() {
 
  // 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');
 
 
       }
 
       }
    });
 
  }
 
 
 
  // Inicializar quando o DOM estiver pronto
 
  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();
 
 
     });
 
     });
 
   }
 
   }
 
});
 
});

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