MediaWiki:Timeless.js: Difference between revisions

From Game Wiki - VortanMU
No edit summary
Tags: Manual revert Reverted
No edit summary
Tag: Manual revert
 
(5 intermediate revisions by the same user not shown)
Line 192: Line 192:
} );
} );
} );
} );
/* Popout menus (header) */
/* ===== Mega-menu estável – Timeless (.mw-portlet) ===== */
mw.loader.using(['jquery']).then(function () {
  try {
    if (window.__megaMenuStable) return;
    window.__megaMenuStable = true;


/* eslint-disable no-jquery/no-fade */
    var NAV_SEL = '#site-navigation .sidebar-inner';
    var isDesktop = function () { return window.innerWidth >= 851; };


$( function () {
    function build() {
var toggleTime = 200;
      var $container = $(NAV_SEL);
      if (!$container.length) return;


// Open the various menus
      // limpa qualquer resíduo de execuções anteriores
$( '#user-tools h2' ).on( 'click', function () {
      $container.find('h3.has-mega').removeClass('has-mega active');
if ( $( window ).width() < 851 ) {
      $container.find('ul.submenu').remove();
$( '#personal-inner, #menus-cover' ).fadeToggle( toggleTime );
      $(document).off('.megamenu');
}
      $(window).off('.megamenu');
} );
$( '#site-navigation h2' ).on( 'click', function () {
if ( $( window ).width() < 851 ) {
$( '#site-navigation .sidebar-inner, #menus-cover' ).fadeToggle( toggleTime );
}
} );
$( '#site-tools h2' ).on( 'click', function () {
if ( $( window ).width() < 851 ) {
$( '#site-tools .sidebar-inner, #menus-cover' ).fadeToggle( toggleTime );
}
} );
$( '#ca-more' ).on( 'click', function () {
$( '#page-tools .sidebar-inner' ).css( 'top', $( '#ca-more' ).offset().top + 25 );
if ( $( window ).width() < 851 ) {
$( '#page-tools .sidebar-inner, #menus-cover' ).fadeToggle( toggleTime );
}
} );
$( '#ca-languages' ).on( 'click', function () {
$( '#other-languages .sidebar-inner' ).css( 'top', $( '#ca-languages' ).offset().top + 25 );
if ( $( window ).width() < 851 ) {
$( '#other-languages .sidebar-inner, #menus-cover' ).fadeToggle( toggleTime );
}
} );


// Close menus on click outside
      // para cada seção (portlet)
$( document ).on( 'click touchstart', function ( e ) {
      $container.find('.mw-portlet').each(function () {
if ( $( e.target ).closest( '#menus-cover' ).length > 0 ) {
        var $portlet = $(this);
$( '#personal-inner' ).fadeOut( toggleTime );
        var $h3 = $portlet.children('h3').first();
$( '.sidebar-inner' ).fadeOut( toggleTime );
        var $ul = $portlet.children('ul').first();
$( '#menus-cover' ).fadeOut( toggleTime );
        if (!$ul.length) $ul = $portlet.find('> .mw-portlet-body > ul').first();
}
        if (!$h3.length || !$ul.length) return;
} );
} );


// Melhoria do comportamento dos submenus multi-coluna
        var $links = $ul.find('> li > a');
$(document).ready(function() {
        if (!$links.length) return;


// Função para aplicar classes de coluna dinamicamente se necessário
        // marca o título como "tem mega"
function adjustSubmenuColumns() {
        $h3.addClass('has-mega');
$('.submenu').each(function() {
const $submenu = $(this);
const itemCount = $submenu.find('li').length;


// Remove classes existentes
        // define colunas dinamicamente
$submenu.removeClass('submenu-2-columns submenu-3-columns submenu-4-columns');
        var n = $links.length;
        var cls = 'submenu';
        if (n > 20) cls += ' submenu-4-columns';
        else if (n > 12) cls += ' submenu-3-columns';
        else if (n > 6) cls += ' submenu-2-columns';


// Aplica classe baseada na quantidade de itens
        // cria o painel
if (itemCount > 20) {
        var $submenu = $('<ul/>', { 'class': cls }).appendTo($portlet);
$submenu.addClass('submenu-4-columns');
        $links.each(function () {
} else if (itemCount > 12) {
          $('<li/>').append($(this).clone()).appendTo($submenu);
$submenu.addClass('submenu-3-columns');
        });
} else if (itemCount > 6) {
$submenu.addClass('submenu-2-columns');
}
});
}


// Aplica as classes na inicialização
        // esconde a lista original e o painel
adjustSubmenuColumns();
        $ul.hide();
        $submenu.hide();


// Comportamento móvel para submenus
        // posiciona ao lado da barra e alinhado ao título
if ($(window).width() <= 850) {
        function reposition() {
$('li.has-submenu > a').on('click', function(e) {
          var left = $container.outerWidth() + 12;          // distância da sidebar
e.preventDefault();
          var top  = $h3.position().top - 6;                 // alinhado pela altura do h3
var $parent = $(this).parent();
          $submenu.css({ left: left, top: top });
        }


if ($parent.hasClass('active')) {
        function open() {
$parent.removeClass('active');
          // fecha outros
} else {
          $container.find('h3.has-mega').not($h3).removeClass('active');
// Fecha outros menus abertos
          $container.find('ul.submenu').not($submenu).hide();
$('li.has-submenu.active').removeClass('active');
$parent.addClass('active');
}
});
}


// Força aplicação de colunas em navegadores específicos
          $h3.addClass('active');
function forceColumnLayout() {
          reposition();
// Verifica se as colunas não estão sendo aplicadas corretamente
          $submenu.stop(true, true).fadeIn(90);
$('.submenu.submenu-2-columns').each(function() {
        }
const $this = $(this);
if ($this.is(':visible')) {
const width = $this.width();
const items = $this.find('li');


// Se parece que não está em colunas, força o CSS
        function close() {
if (items.length > 6 && width < 400) {
          $h3.removeClass('active');
$this.css({
          $submenu.stop(true, true).fadeOut(90);
'column-count': '2',
        }
'column-gap': '20px',
'min-width': '450px'
});
}
}
});


$('.submenu.submenu-3-columns').each(function() {
        function toggle() {
const $this = $(this);
          ($submenu.is(':visible')) ? close() : open();
if ($this.is(':visible')) {
        }
const width = $this.width();
const items = $this.find('li');


if (items.length > 12 && width < 550) {
        // hover/click com delay pra não sumir no caminho do mouse
$this.css({
        var closeTimer = null;
'column-count': '3',
'column-gap': '20px',
'min-width': '600px'
});
}
}
});


$('.submenu.submenu-4-columns').each(function() {
        $h3.on('mouseenter.megamenu', function () {
const $this = $(this);
          if (isDesktop()) open();
if ($this.is(':visible')) {
        }).on('mouseleave.megamenu', function () {
const width = $this.width();
          if (isDesktop()) {
const items = $this.find('li');
            closeTimer = setTimeout(function () {
              if (!$submenu.is(':hover') && !$h3.is(':hover')) close();
            }, 120);
          }
        }).on('click.megamenu', function (e) {
          if (!isDesktop()) { e.preventDefault(); toggle(); }
        });


if (items.length > 20 && width < 700) {
        $submenu.on('mouseenter.megamenu', function () {
$this.css({
          if (isDesktop()) { clearTimeout(closeTimer); open(); }
'column-count': '4',
        }).on('mouseleave.megamenu', function () {
'column-gap': '20px',
          if (isDesktop()) {
'min-width': '750px'
            closeTimer = setTimeout(function () {
});
              if (!$h3.is(':hover')) close();
}
            }, 120);
}
          }
});
        });
}


// Aplica verificação quando submenus são mostrados
        $(window).on('resize.megamenu', reposition);
$('li.has-submenu').on('mouseenter', function() {
      });
setTimeout(forceColumnLayout, 50);
});


// Reaplica classes quando a janela é redimensionada
      // fecha clicando fora
$(window).on('resize', function() {
      $(document).on('click.megamenu', function (e) {
adjustSubmenuColumns();
        if ($(e.target).closest(NAV_SEL).length === 0) {
setTimeout(forceColumnLayout, 100);
          var $c = $(NAV_SEL);
});
          $c.find('h3.has-mega').removeClass('active');
          $c.find('ul.submenu').hide();
        }
      });
    }


// Garante que o comportamento seja aplicado em conteúdo carregado dinamicamente
    mw.hook('wikipage.content').add(build);
if (typeof MutationObserver !== 'undefined') {
    $(build);
const observer = new MutationObserver(function(mutations) {
    console.log('[MegaMenu] OK');
mutations.forEach(function(mutation) {
  } catch (err) {
if (mutation.addedNodes.length) {
    console.error('[MegaMenu] erro', err);
// Verifica se algum dos nós adicionados contém submenus
  }
$(mutation.addedNodes).find('.submenu').each(function() {
adjustSubmenuColumns();
});
}
});
});
 
observer.observe(document.body, { childList: true, subtree: true });
}
 
// Função de debug para verificar se as colunas estão funcionando
window.debugSubmenus = function() {
$('.submenu').each(function() {
const $this = $(this);
const itemCount = $this.find('li').length;
const isVisible = $this.is(':visible');
const columnCount = $this.css('column-count');
const width = $this.width();
 
console.log('Submenu:', {
items: itemCount,
visible: isVisible,
columnCount: columnCount,
width: width,
classes: $this.attr('class')
});
});
};
});
// Adiciona efeitos de interação
document.addEventListener('DOMContentLoaded', function() {
const guideItems = document.querySelectorAll('.mw-guide-item');
 
guideItems.forEach(item => {
item.addEventListener('mouseenter', function() {
this.style.transform = 'translateY(-3px)';
});
 
item.addEventListener('mouseleave', function() {
this.style.transform = 'translateY(0)';
});
 
item.addEventListener('click', function(e) {
// Adiciona efeito de clique
this.style.transform = 'translateY(1px)';
setTimeout(() => {
this.style.transform = 'translateY(-3px)';
}, 100);
});
});
});
// JavaScript para Cards com Imagem - compatível com sistema existente
$(document).ready(function() {
 
// Função para gerenciar cards com imagem (reutiliza lógica existente)
function initImageCards() {
const imageCards = $('.mw-image-card');
 
// Aplica os mesmos efeitos dos guias existentes
imageCards.each(function() {
const $card = $(this);
 
// Efeitos hover melhorados
$card.on('mouseenter', function() {
$(this).css({
'transform': 'translateY(-8px) scale(1.02)',
'transition': 'all 0.3s ease'
});
});
 
$card.on('mouseleave', function() {
$(this).css({
'transform': 'translateY(0) scale(1)',
'transition': 'all 0.3s ease'
});
});
 
// Efeito de clique
$card.on('click', function() {
$(this).css('transform', 'translateY(-2px) scale(0.98)');
setTimeout(() => {
$(this).css('transform', 'translateY(-8px) scale(1.02)');
}, 150);
});
});
}
 
// Função para gerenciar carregamento de imagens
function handleImageLoading() {
$('.mw-card-image img').each(function() {
const $img = $(this);
const $container = $img.parent();
 
// Adiciona classe de loading
$container.addClass('loading');
 
// Quando a imagem carregar
$img.on('load', function() {
$container.removeClass('loading');
});
 
// Se a imagem falhar ao carregar
$img.on('error', function() {
$container.removeClass('loading');
// Mantém o gradiente de fundo como fallback
$img.hide();
});
 
// Se a imagem já estiver carregada (cache)
if (this.complete) {
$container.removeClass('loading');
}
});
}
 
// Função de responsividade para cards com imagem
function adjustImageGrid() {
const imageGrid = $('.mw-image-grid');
const width = $(window).innerWidth;
 
if (width < 480) {
imageGrid.css('grid-template-columns', '1fr');
} else if (width < 768) {
imageGrid.css('grid-template-columns', 'repeat(auto-fit, minmax(250px, 1fr))');
} else {
imageGrid.css('grid-template-columns', 'repeat(auto-fit, minmax(300px, 1fr))');
}
}
 
// Função para lazy loading de imagens (opcional)
function lazyLoadImages() {
if ('IntersectionObserver' in window) {
const imageObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
const dataSrc = img.getAttribute('data-src');
if (dataSrc) {
img.src = dataSrc;
img.removeAttribute('data-src');
imageObserver.unobserve(img);
}
}
});
});
 
$('.mw-card-image img[data-src]').each(function() {
imageObserver.observe(this);
});
}
}
 
// Integração com sistema existente de guias
function integrateWithExistingSystem() {
// Estende a funcionalidade existente para incluir cards de imagem
if (typeof window.adjustGuideGrid === 'function') {
const originalAdjustGuideGrid = window.adjustGuideGrid;
window.adjustGuideGrid = function() {
originalAdjustGuideGrid();
adjustImageGrid();
};
} else {
window.adjustGuideGrid = adjustImageGrid;
}
 
// Adiciona cards de imagem ao sistema de debug existente
if (typeof window.debugSubmenus === 'function') {
const originalDebug = window.debugSubmenus;
window.debugImageCards = function() {
$('.mw-image-card').each(function() {
const $card = $(this);
const text = $card.find('.mw-card-text').text();
const hasImage = $card.find('img').length > 0;
const imageLoaded = hasImage ? $card.find('img')[0].complete : false;
 
console.log('Image Card:', {
text: text,
hasImage: hasImage,
imageLoaded: imageLoaded,
dimensions: {
width: $card.width(),
height: $card.height()
}
});
});
 
// Chama debug original se existir
if (originalDebug) originalDebug();
};
}
}
 
// Inicialização
initImageCards();
handleImageLoading();
adjustImageGrid();
lazyLoadImages();
integrateWithExistingSystem();
 
// Event listeners
$(window).on('resize', function() {
adjustImageGrid();
});
 
// Observa mudanças no DOM para novos cards adicionados dinamicamente
if (typeof MutationObserver !== 'undefined') {
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.addedNodes.length) {
$(mutation.addedNodes).find('.mw-image-card').each(function() {
initImageCards();
handleImageLoading();
});
}
});
});
 
observer.observe(document.body, { childList: true, subtree: true });
}
});
});
// Função global para adicionar novos cards dinamicamente
window.addImageCard = function(container, link, imageSrc, text, bgClass) {
const cardHtml = `
        <a href="${link}" class="mw-image-card">
            <div class="mw-card-image ${bgClass || ''}">
                <img src="${imageSrc}" alt="${text}" />
            </div>
            <div class="mw-card-text">${text}</div>
        </a>
    `;
$(container).find('.mw-image-grid').append(cardHtml);
// Reinicializa funcionalidades para o novo card
const $newCard = $(container).find('.mw-image-card').last();
$newCard.trigger('initImageCard');
};
// Função para tornar todas as tabelas responsivas
function makeTablesResponsive() {
// Seleciona todas as tabelas da página
const tables = document.querySelectorAll('table');
tables.forEach(table => {
// Verifica se a tabela tem cabeçalhos (th)
let headers = Array.from(table.querySelectorAll('th')).map(th => th.textContent.trim());
// Se não houver cabeçalhos, tenta usar a primeira linha como cabeçalho
if (headers.length === 0) {
const firstRow = table.querySelector('tr');
if (firstRow) {
const cells = firstRow.querySelectorAll('td');
headers.push(...Array.from(cells).map(cell => cell.textContent.trim()));
}
}
// Para tabelas com cabeçalhos em múltiplas linhas, tentamos capturar todos
if (table.querySelectorAll('thead tr').length > 1) {
// Para tabelas com cabeçalhos complexos, usamos a última linha de cabeçalhos
const headerRows = table.querySelectorAll('thead tr');
const lastHeaderRow = headerRows[headerRows.length - 1];
headers = Array.from(lastHeaderRow.querySelectorAll('th')).map(th => th.textContent.trim());
}
// Para cada linha da tabela, adiciona atributos data-label às células
const rows = table.querySelectorAll('tr');
// Começa a partir da primeira linha após os cabeçalhos
// Se estamos em uma tabela sem thead ou com th, começamos nas linhas de tbody
// Se tabela tiver thead, ignoramos as linhas de cabeçalho
let startRow = 0;
if (table.querySelector('thead')) {
startRow = table.querySelectorAll('thead tr').length;
} else if (headers.length > 0 && table.querySelectorAll('th').length > 0) {
// Se não tem thead mas tem th, assumimos primeira linha como cabeçalho
startRow = 1;
}
for (let i = startRow; i < rows.length; i++) {
const cells = rows[i].querySelectorAll('td');
cells.forEach((cell, index) => {
if (index < headers.length && headers[index]) {
cell.setAttribute('data-label', headers[index]);
}
});
}
});
}
// Executa quando o DOM estiver pronto
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', makeTablesResponsive);
} else {
makeTablesResponsive();
}
// Verifica novamente após o carregamento da página (para conteúdo carregado dinamicamente)
window.addEventListener('load', makeTablesResponsive);
// Para lidar com conteúdo adicionado dinamicamente (como em edições AJAX)
// Observe mutações no DOM
if (typeof MutationObserver !== 'undefined') {
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.addedNodes.length) {
makeTablesResponsive();
}
});
});
// Observe mudanças no corpo do documento
observer.observe(document.body, { childList: true, subtree: true });
}

Latest revision as of 09:01, 17 November 2025

$( function () {
	// sidebar-chunk only applies to desktop-small, but the toggles are hidden at
	// other resolutions regardless and the css overrides any visible effects.
	var $dropdowns = $( '#personal, #p-variants-desktop, .sidebar-chunk' );

	/**
	 * Desktop menu click-toggling
	 *
	 * We're not even checking if it's desktop because the classes in play have no effect
	 * on mobile regardless... this may break things at some point, though.
	 */

	/**
	 * Close all dropdowns
	 */
	function closeOpen() {
		$dropdowns.removeClass( 'dropdown-active' );
	}

	/**
	 * Click behaviour
	 */
	$dropdowns.on( 'click', function ( e ) {
		// Check if it's already open so we don't open it again
		// eslint-disable-next-line no-jquery/no-class-state
		if ( $( this ).hasClass( 'dropdown-active' ) ) {
			if ( $( e.target ).closest( $( 'h2, #p-variants-desktop h3' ) ).length > 0 ) {
				// treat reclick on the header as a toggle
				closeOpen();
			}
			// Clicked inside an open menu; don't do anything
		} else {
			closeOpen();
			e.stopPropagation(); // stop hiding it!
			$( this ).addClass( 'dropdown-active' );
		}
	} );
	$( document ).on( 'click', function ( e ) {
		if ( $( e.target ).closest( $dropdowns ).length > 0 ) {
			// Clicked inside an open menu; don't close anything
		} else {
			closeOpen();
		}
	} );
} );

mw.hook( 'wikipage.content' ).add( function ( $content ) {
	// Gotta wrap them for this to work; maybe later the parser etc will do this for us?!
	$content.find( 'div > table:not( table table )' ).wrap( '<div class="content-table-wrapper"><div class="content-table"></div></div>' );
	$content.find( '.content-table-wrapper' ).prepend( '<div class="content-table-left"></div><div class="content-table-right"></div>' );

	/**
	 * Set up borders for experimental overflowing table scrolling
	 *
	 * I have no idea what I'm doing.
	 *
	 * @param {jQuery} $table
	 */
	function setScrollClass( $table ) {
		var $tableWrapper = $table.parent(),
			// wtf browser rtl implementations
			scroll = Math.abs( $tableWrapper.scrollLeft() );

		$tableWrapper.parent()
			// 1 instead of 0 because of weird rtl rounding errors or something
			.toggleClass( 'scroll-left', scroll > 1 )
			.toggleClass( 'scroll-right', $table.outerWidth() - $tableWrapper.innerWidth() - scroll > 1 );
	}

	$content.find( '.content-table' ).on( 'scroll', function () {
		setScrollClass( $( this ).children( 'table' ).first() );

		if ( $content.attr( 'dir' ) === 'rtl' ) {
			$( this ).find( 'caption' ).css( 'margin-right', Math.abs( $( this ).scrollLeft() ) + 'px' );
		} else {
			$( this ).find( 'caption' ).css( 'margin-left', $( this ).scrollLeft() + 'px' );
		}
	} );

	/**
	 * Mark overflowed tables for scrolling
	 */
	function unOverflowTables() {
		$content.find( '.content-table > table' ).each( function () {
			var $table = $( this ),
				$wrapper = $table.parent().parent();
			if ( $table.outerWidth() > $wrapper.outerWidth() ) {
				$wrapper.addClass( 'overflowed' );
				setScrollClass( $table );
			} else {
				$wrapper.removeClass( 'overflowed scroll-left scroll-right fixed-scrollbar-container' );
			}
		} );

		// Set up sticky captions
		$content.find( '.content-table > table > caption' ).each( function () {
			var $container, tableHeight,
				$table = $( this ).parent(),
				$wrapper = $table.parent().parent();

			if ( $table.outerWidth() > $wrapper.outerWidth() ) {
				$container = $( this ).parents( '.content-table-wrapper' );
				$( this ).width( $content.width() );
				tableHeight = $container.innerHeight() - $( this ).outerHeight();

				$container.find( '.content-table-left' ).height( tableHeight );
				$container.find( '.content-table-right' ).height( tableHeight );
			}
		} );
	}

	unOverflowTables();
	$( window ).on( 'resize', unOverflowTables );

	/**
	 * Sticky scrollbars maybe?!
	 */
	$content.find( '.content-table' ).each( function () {
		var $table, $tableWrapper, $spoof, $scrollbar;

		$tableWrapper = $( this );
		$table = $tableWrapper.children( 'table' ).first();

		// Assemble our silly crap and add to page
		$scrollbar = $( '<div>' ).addClass( 'content-table-scrollbar inactive' ).width( $content.width() );
		$spoof = $( '<div>' ).addClass( 'content-table-spoof' ).width( $table.outerWidth() );
		$tableWrapper.parent().prepend( $scrollbar.prepend( $spoof ) );
	} );

	/**
	 * Scoll table when scrolling scrollbar and visa-versa lololol wut
	 */
	$content.find( '.content-table' ).on( 'scroll', function () {
		// Only do this here if we're not already mirroring the spoof
		var $mirror = $( this ).siblings( '.inactive' ).first();

		$mirror.scrollLeft( $( this ).scrollLeft() );
	} );
	$content.find( '.content-table-scrollbar' ).on( 'scroll', function () {
		var $mirror = $( this ).siblings( '.content-table' ).first();

		// Only do this here if we're not already mirroring the table
		// eslint-disable-next-line no-jquery/no-class-state
		if ( !$( this ).hasClass( 'inactive' ) ) {
			$mirror.scrollLeft( $( this ).scrollLeft() );
		}
	} );

	/**
	 * Set active when actually over the table it applies to...
	 */
	function determineActiveSpoofScrollbars() {
		$content.find( '.overflowed .content-table' ).each( function () {
			var $scrollbar = $( this ).siblings( '.content-table-scrollbar' ).first();

			// Skip caption
			var captionHeight = $( this ).find( 'caption' ).outerHeight() || 0;
			if ( captionHeight ) {
				// Pad slightly for reasons
				captionHeight += 8;
			}

			var tableTop = $( this ).offset().top,
				tableBottom = tableTop + $( this ).outerHeight(),
				viewBottom = window.scrollY + document.documentElement.clientHeight,
				active = tableTop + captionHeight < viewBottom && tableBottom > viewBottom;
			$scrollbar.toggleClass( 'inactive', !active );
		} );
	}

	determineActiveSpoofScrollbars();
	$( window ).on( 'scroll resize', determineActiveSpoofScrollbars );


	function showContent(id) {
		const conteudos = document.querySelectorAll('.nav-content');
		conteudos.forEach((div) => {
			div.classList.remove('show-content');
		});
		document.getElementById(id).classList.add('show-content');
	}

	/**
	 * Make sure tablespoofs remain correctly-sized?
	 */
	$( window ).on( 'resize', function () {
		$content.find( '.content-table-scrollbar' ).each( function () {
			var width = $( this ).siblings().first().find( 'table' ).first().width();
			$( this ).find( '.content-table-spoof' ).first().width( width );
			$( this ).width( $content.width() );
		} );
	} );
} );
/* ===== Mega-menu estável – Timeless (.mw-portlet) ===== */
mw.loader.using(['jquery']).then(function () {
  try {
    if (window.__megaMenuStable) return;
    window.__megaMenuStable = true;

    var NAV_SEL = '#site-navigation .sidebar-inner';
    var isDesktop = function () { return window.innerWidth >= 851; };

    function build() {
      var $container = $(NAV_SEL);
      if (!$container.length) return;

      // limpa qualquer resíduo de execuções anteriores
      $container.find('h3.has-mega').removeClass('has-mega active');
      $container.find('ul.submenu').remove();
      $(document).off('.megamenu');
      $(window).off('.megamenu');

      // para cada seção (portlet)
      $container.find('.mw-portlet').each(function () {
        var $portlet = $(this);
        var $h3 = $portlet.children('h3').first();
        var $ul = $portlet.children('ul').first();
        if (!$ul.length) $ul = $portlet.find('> .mw-portlet-body > ul').first();
        if (!$h3.length || !$ul.length) return;

        var $links = $ul.find('> li > a');
        if (!$links.length) return;

        // marca o título como "tem mega"
        $h3.addClass('has-mega');

        // define colunas dinamicamente
        var n = $links.length;
        var cls = 'submenu';
        if (n > 20) cls += ' submenu-4-columns';
        else if (n > 12) cls += ' submenu-3-columns';
        else if (n > 6) cls += ' submenu-2-columns';

        // cria o painel
        var $submenu = $('<ul/>', { 'class': cls }).appendTo($portlet);
        $links.each(function () {
          $('<li/>').append($(this).clone()).appendTo($submenu);
        });

        // esconde a lista original e o painel
        $ul.hide();
        $submenu.hide();

        // posiciona ao lado da barra e alinhado ao título
        function reposition() {
          var left = $container.outerWidth() + 12;          // distância da sidebar
          var top  = $h3.position().top - 6;                 // alinhado pela altura do h3
          $submenu.css({ left: left, top: top });
        }

        function open() {
          // fecha outros
          $container.find('h3.has-mega').not($h3).removeClass('active');
          $container.find('ul.submenu').not($submenu).hide();

          $h3.addClass('active');
          reposition();
          $submenu.stop(true, true).fadeIn(90);
        }

        function close() {
          $h3.removeClass('active');
          $submenu.stop(true, true).fadeOut(90);
        }

        function toggle() {
          ($submenu.is(':visible')) ? close() : open();
        }

        // hover/click com delay pra não sumir no caminho do mouse
        var closeTimer = null;

        $h3.on('mouseenter.megamenu', function () {
          if (isDesktop()) open();
        }).on('mouseleave.megamenu', function () {
          if (isDesktop()) {
            closeTimer = setTimeout(function () {
              if (!$submenu.is(':hover') && !$h3.is(':hover')) close();
            }, 120);
          }
        }).on('click.megamenu', function (e) {
          if (!isDesktop()) { e.preventDefault(); toggle(); }
        });

        $submenu.on('mouseenter.megamenu', function () {
          if (isDesktop()) { clearTimeout(closeTimer); open(); }
        }).on('mouseleave.megamenu', function () {
          if (isDesktop()) {
            closeTimer = setTimeout(function () {
              if (!$h3.is(':hover')) close();
            }, 120);
          }
        });

        $(window).on('resize.megamenu', reposition);
      });

      // fecha clicando fora
      $(document).on('click.megamenu', function (e) {
        if ($(e.target).closest(NAV_SEL).length === 0) {
          var $c = $(NAV_SEL);
          $c.find('h3.has-mega').removeClass('active');
          $c.find('ul.submenu').hide();
        }
      });
    }

    mw.hook('wikipage.content').add(build);
    $(build);
    console.log('[MegaMenu] OK');
  } catch (err) {
    console.error('[MegaMenu] erro', err);
  }
});