MediaWiki:Timeless.js: Difference between revisions

From Game Wiki - VortanMU
No edit summary
Tag: Manual revert
No edit summary
Line 1: Line 1:
$( function () {
/* ==============================
// sidebar-chunk only applies to desktop-small, but the toggles are hidden at
  VortanMU - Timeless sidebar fix
// other resolutions regardless and the css overrides any visible effects.
  Purpose:
var $dropdowns = $( '#personal, #p-variants-desktop, .sidebar-chunk' );
  1) Remove legacy "MEGAMENU" DOM mutations (ul.submenu + display:none on original lists)
  2) Make left portlets collapsible (modern button-like headers)


/**
  Paste this into: MediaWiki:Timeless.js
* 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.
*/


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


/**
  function qsa(root, sel) {
* Click behaviour
    return Array.prototype.slice.call((root || document).querySelectorAll(sel));
*/
  }
$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 ) {
  function removeLegacySubmenus(portlet) {
// Gotta wrap them for this to work; maybe later the parser etc will do this for us?!
    // remove any injected submenu lists
$content.find( 'div > table:not( table table )' ).wrap( '<div class="content-table-wrapper"><div class="content-table"></div></div>' );
    qsa(portlet, 'ul.submenu').forEach(function (ul) { ul.remove(); });
$content.find( '.content-table-wrapper' ).prepend( '<div class="content-table-left"></div><div class="content-table-right"></div>' );


/**
    // re-show the original list if a legacy script hid it
* Set up borders for experimental overflowing table scrolling
    var body = portlet.querySelector('.mw-portlet-body');
*
    if (!body) return;
* 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()
    var ul = body.querySelector('ul');
// 1 instead of 0 because of weird rtl rounding errors or something
    if (!ul) return;
.toggleClass( 'scroll-left', scroll > 1 )
.toggleClass( 'scroll-right', $table.outerWidth() - $tableWrapper.innerWidth() - scroll > 1 );
}


$content.find( '.content-table' ).on( 'scroll', function () {
    // clear inline styles like: style="display:none"
setScrollClass( $( this ).children( 'table' ).first() );
    ul.style.display = '';
 
    ul.hidden = false;
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
  function ensureHeaderIsToggle(portlet) {
$content.find( '.content-table > table > caption' ).each( function () {
    var header = portlet.querySelector('h3');
var $container, tableHeight,
    var body = portlet.querySelector('.mw-portlet-body');
$table = $( this ).parent(),
    if (!header || !body) return;
$wrapper = $table.parent().parent();


if ( $table.outerWidth() > $wrapper.outerWidth() ) {
    if (!header.classList.contains('vm-portlet__header')) {
$container = $( this ).parents( '.content-table-wrapper' );
      header.classList.add('vm-portlet__header');
$( this ).width( $content.width() );
      header.setAttribute('tabindex', '0');
tableHeight = $container.innerHeight() - $( this ).outerHeight();
      header.setAttribute('role', 'button');
      header.setAttribute('aria-expanded', 'false');


$container.find( '.content-table-left' ).height( tableHeight );
      var onToggle = function () {
$container.find( '.content-table-right' ).height( tableHeight );
        var isOpen = portlet.classList.toggle('is-open');
}
        header.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
} );
      };
}


unOverflowTables();
      header.addEventListener('click', onToggle);
$( window ).on( 'resize', unOverflowTables );
      header.addEventListener('keydown', function (e) {
 
        if (e.key === 'Enter' || e.key === ' ') {
/**
           e.preventDefault();
* Sticky scrollbars maybe?!
           onToggle();
*/
$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() {
  function normalizeLeftSidebar() {
          $h3.removeClass('active');
    var nav = document.getElementById('mw-site-navigation');
          $submenu.stop(true, true).fadeOut(90);
    if (!nav) return;
        }
 
        function toggle() {
          ($submenu.is(':visible')) ? close() : open();
        }


        // hover/click com delay pra não sumir no caminho do mouse
    nav.classList.add('vm-nav');
        var closeTimer = null;


        $h3.on('mouseenter.megamenu', function () {
    var portlets = qsa(nav, '.sidebar-inner .mw-portlet[role="navigation"]');
          if (isDesktop()) open();
    portlets.forEach(function (p, idx) {
        }).on('mouseleave.megamenu', function () {
      p.classList.add('vm-portlet');
          if (isDesktop()) {
      removeLegacySubmenus(p);
            closeTimer = setTimeout(function () {
      ensureHeaderIsToggle(p);
              if (!$submenu.is(':hover') && !$h3.is(':hover')) close();
            }, 120);
          }
        }).on('click.megamenu', function (e) {
          if (!isDesktop()) { e.preventDefault(); toggle(); }
        });


        $submenu.on('mouseenter.megamenu', function () {
      // default: open first group only (can change to open all)
          if (isDesktop()) { clearTimeout(closeTimer); open(); }
      if (idx === 0) p.classList.add('is-open');
        }).on('mouseleave.megamenu', function () {
    });
          if (isDesktop()) {
            closeTimer = setTimeout(function () {
              if (!$h3.is(':hover')) close();
            }, 120);
          }
        });


        $(window).on('resize.megamenu', reposition);
    // if some other script tries to inject mega-menu again after load, kill it
      });
    var inner = nav.querySelector('.sidebar-inner');
    if (!inner) return;


      // fecha clicando fora
    if (!inner.__vmObserver) {
       $(document).on('click.megamenu', function (e) {
       var obs = new MutationObserver(function () {
         if ($(e.target).closest(NAV_SEL).length === 0) {
        var injected = inner.querySelector('ul.submenu');
           var $c = $(NAV_SEL);
         if (injected) {
          $c.find('h3.has-mega').removeClass('active');
           qsa(inner, '.mw-portlet').forEach(function (p) {
           $c.find('ul.submenu').hide();
            removeLegacySubmenus(p);
           });
         }
         }
       });
       });
      obs.observe(inner, { childList: true, subtree: true });
      inner.__vmObserver = obs;
     }
     }
  }


     mw.hook('wikipage.content').add(build);
  function runSoon() {
    $(build);
    normalizeLeftSidebar();
     console.log('[MegaMenu] OK');
    setTimeout(normalizeLeftSidebar, 250);
   } catch (err) {
    setTimeout(normalizeLeftSidebar, 1000);
    console.error('[MegaMenu] erro', err);
  }
 
  if (window.mw && mw.hook) {
     mw.hook('wikipage.content').add(function () {
      runSoon();
     });
   } else {
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', runSoon);
    } else {
      runSoon();
    }
   }
   }
});
})();

Revision as of 05:57, 16 January 2026

/* ==============================
   VortanMU - Timeless sidebar fix
   Purpose:
   1) Remove legacy "MEGAMENU" DOM mutations (ul.submenu + display:none on original lists)
   2) Make left portlets collapsible (modern button-like headers)

   Paste this into: MediaWiki:Timeless.js
   ============================== */

(function () {
  'use strict';

  function qsa(root, sel) {
    return Array.prototype.slice.call((root || document).querySelectorAll(sel));
  }

  function removeLegacySubmenus(portlet) {
    // remove any injected submenu lists
    qsa(portlet, 'ul.submenu').forEach(function (ul) { ul.remove(); });

    // re-show the original list if a legacy script hid it
    var body = portlet.querySelector('.mw-portlet-body');
    if (!body) return;

    var ul = body.querySelector('ul');
    if (!ul) return;

    // clear inline styles like: style="display:none"
    ul.style.display = '';
    ul.hidden = false;
  }

  function ensureHeaderIsToggle(portlet) {
    var header = portlet.querySelector('h3');
    var body = portlet.querySelector('.mw-portlet-body');
    if (!header || !body) return;

    if (!header.classList.contains('vm-portlet__header')) {
      header.classList.add('vm-portlet__header');
      header.setAttribute('tabindex', '0');
      header.setAttribute('role', 'button');
      header.setAttribute('aria-expanded', 'false');

      var onToggle = function () {
        var isOpen = portlet.classList.toggle('is-open');
        header.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
      };

      header.addEventListener('click', onToggle);
      header.addEventListener('keydown', function (e) {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          onToggle();
        }
      });
    }
  }

  function normalizeLeftSidebar() {
    var nav = document.getElementById('mw-site-navigation');
    if (!nav) return;

    nav.classList.add('vm-nav');

    var portlets = qsa(nav, '.sidebar-inner .mw-portlet[role="navigation"]');
    portlets.forEach(function (p, idx) {
      p.classList.add('vm-portlet');
      removeLegacySubmenus(p);
      ensureHeaderIsToggle(p);

      // default: open first group only (can change to open all)
      if (idx === 0) p.classList.add('is-open');
    });

    // if some other script tries to inject mega-menu again after load, kill it
    var inner = nav.querySelector('.sidebar-inner');
    if (!inner) return;

    if (!inner.__vmObserver) {
      var obs = new MutationObserver(function () {
        var injected = inner.querySelector('ul.submenu');
        if (injected) {
          qsa(inner, '.mw-portlet').forEach(function (p) {
            removeLegacySubmenus(p);
          });
        }
      });
      obs.observe(inner, { childList: true, subtree: true });
      inner.__vmObserver = obs;
    }
  }

  function runSoon() {
    normalizeLeftSidebar();
    setTimeout(normalizeLeftSidebar, 250);
    setTimeout(normalizeLeftSidebar, 1000);
  }

  if (window.mw && mw.hook) {
    mw.hook('wikipage.content').add(function () {
      runSoon();
    });
  } else {
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', runSoon);
    } else {
      runSoon();
    }
  }
})();