MediaWiki:Mobile.js

Revision as of 00:51, 4 December 2025 by Wikilah admin (talk | contribs)

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
// CapSach — Mobile TOC overlay (all skins; phone widths)
(function () {
  // Don’t run on very wide screens (tablet/desktop have native TOC)
  if (window.matchMedia('(min-width: 768px)').matches) return;

  // Only on normal content pages
  if (window.mw && mw.config && mw.config.get) {
    var isAllowed = mw.config.get('wgIsArticle') || mw.config.get('wgIsMainPage');
    if (!isAllowed) return;
  }

  // Find the content root; MobileFrontend restructures DOM, so be flexible
  var root =
    document.querySelector('#mw-content-text .mw-parser-output') ||
    document.querySelector('.mw-parser-output') ||
    document.getElementById('mw-content-text') ||
    document.querySelector('#content') ||
    document.body;

  // Collect headings (H2–H6). Prefer spans with .mw-headline (stable anchor ids)
  var items = [];
  var headings = root.querySelectorAll('h2, h3, h4, h5, h6');
  headings.forEach(function (h) {
    var level = parseInt(h.tagName.slice(1), 10);
    if (level < 2 || level > 6) return;
    var headline = h.querySelector('.mw-headline') || h;
    var id = headline.id || h.id;
    var text = (headline.textContent || h.textContent || '').trim();
    if (!id || !text) return;
    items.push({ id: id, text: text, level: level });
  });

  // Show only if there are enough headings to be useful (match core default)
  if (items.length < 1) return;

  // Create trigger button (bottom-left; avoids “Back to top” on bottom-right)
  var btn = document.createElement('button');
  btn.id = 'cps-open-toc';
  btn.type = 'button';
  btn.setAttribute('aria-label', 'Open table of contents');
  btn.innerHTML = '<span class="icon" aria-hidden="true">≡</span><span class="label">TOC</span>';
  document.body.appendChild(btn);

  // Overlay + panel
  var overlay = document.createElement('div');
  overlay.id = 'cps-toc-overlay';
  overlay.setAttribute('aria-hidden', 'true');

  var panel = document.createElement('div');
  panel.id = 'cps-toc-panel';
  panel.setAttribute('role', 'dialog');
  panel.setAttribute('aria-modal', 'true');
  panel.setAttribute('aria-label', 'Table of contents');

  var header = document.createElement('div');
  header.id = 'cps-toc-header';
  header.innerHTML =
    '<h2 id="cps-toc-title">Contents</h2>' +
    '<button id="cps-toc-close" type="button" aria-label="Close">×</button>';

  var list = document.createElement('ul');
  list.id = 'cps-toc-list';

  items.forEach(function (it) {
    var li = document.createElement('li');
    li.setAttribute('data-level', String(it.level));
    var a = document.createElement('a');
    a.href = '#' + it.id;
    a.textContent = it.text;
    li.appendChild(a);
    list.appendChild(li);
  });

  panel.appendChild(header);
  panel.appendChild(list);
  overlay.appendChild(panel);
  document.body.appendChild(overlay);

  // Focus handling
  var lastFocus = null;
  function openOverlay() {
    lastFocus = document.activeElement;
    overlay.classList.add('is-open');
    overlay.setAttribute('aria-hidden', 'false');
    document.body.style.overflow = 'hidden';
    // Focus first link for accessibility
    var firstLink = list.querySelector('a');
    if (firstLink) firstLink.focus({ preventScroll: true });
  }
  function closeOverlay() {
    overlay.classList.remove('is-open');
    overlay.setAttribute('aria-hidden', 'true');
    document.body.style.overflow = '';
    if (lastFocus && lastFocus.focus) lastFocus.focus({ preventScroll: true });
  }

  btn.style.display = 'flex'; // reveal trigger now that we know we have headings
  btn.addEventListener('click', openOverlay);

  overlay.addEventListener('click', function (e) {
    // Click outside the bottom sheet closes
    if (e.target === overlay) closeOverlay();
  });
  overlay.querySelector('#cps-toc-close').addEventListener('click', closeOverlay);

  overlay.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') closeOverlay();
  });

  // Navigate and try to ensure mobile-collapsed sections are visible
  list.addEventListener('click', function (e) {
    var a = e.target.closest('a');
    if (!a) return;
    e.preventDefault();

    var targetId = a.getAttribute('href').slice(1);
    var target = document.getElementById(targetId);
    closeOverlay();

    if (target) {
      try {
        target.scrollIntoView({ behavior: 'smooth', block: 'start' });
      } catch (_) {
        target.scrollIntoView(true);
      }

      // Update URL hash after a tick (so browser back works)
      setTimeout(function () {
        if (history && history.replaceState) {
          history.replaceState(null, '', '#' + targetId);
        } else {
          location.hash = targetId;
        }
      }, 200);

      // MobileFrontend: headings may be inside collapsed sections.
      // Heuristic: click the nearest toggle if present.
      var maybeToggle = target.closest('.collapsible-block, .mf-section') ||
                        target.closest('section');
      if (maybeToggle && maybeToggle.classList.contains('collapsed')) {
        // Try to open; fallback by clicking the first heading inside
        var headingToggle = maybeToggle.querySelector('.section-heading, h2, h3, h4, h5, h6');
        if (headingToggle) headingToggle.click();
      }
    }
  });

  // Re-hide on rotation/resize to tablet/desktop
  window.addEventListener('resize', function () {
    if (window.matchMedia('(min-width: 768px)').matches) {
      btn.style.display = 'none';
      closeOverlay();
    } else {
      btn.style.display = 'flex';
    }
  }, { passive: true });
})();

/* ======================================================= */
/* ADD 'BIZ BOOKS' TO MOBILE SIDEBAR (UNIVERSAL METHOD)    */
/* ======================================================= */

mw.loader.using( ['mediawiki.util', 'jquery'], function () {
    $( function () {
        
        var linkId   = 'mobile-nav-biz-books';
        var linkHref = '/wiki/Biz/Books';
        var linkText = 'Biz Books';

        // Helper function to find the correct menu list
        function findTargetMenu() {
            // 1. Look for the standard Minerva menu class
            var $lists = $( '.menu ul, .navigation-drawer ul' );

            // 2. Filter to find the list that actually contains the "Home" or "Random" links
            // This prevents us from injecting into the wrong list (like the user settings)
            var $target = $lists.filter(function() {
                // Look for links to Main_Page or Random inside this UL
                return $(this).find('a[href*="Main_Page"], a[href*="Random"]').length > 0;
            });

            // If found, return the first match. If not, fallback to the first UL in the drawer.
            return $target.length ? $target.first() : $lists.first();
        }

        function injectLink() {
            var $menu = findTargetMenu();
            
            // If no menu is found, or if our link already exists, stop.
            if ( $menu.length === 0 || $menu.find( '#' + linkId ).length > 0 ) return;

            console.log( 'BizSlash: Valid menu found. Injecting...' );

            var $newItem = $( '<li>' )
                .addClass( 'mw-ui-icon-extra' )
                .attr( 'id', linkId );

            var $newLink = $( '<a>' )
                .attr( 'href', linkHref )
                // We use 'mw-ui-icon-minerva-list' as a fallback icon because it exists in all versions
                .addClass( 'mw-ui-icon mw-ui-icon-before mw-ui-icon-minerva-list' ) 
                .text( linkText )
                // Force visibility in case classes fail
                .css({
                    'display': 'block',
                    'font-weight': 'bold' 
                });

            $newItem.append( $newLink );
            
            // PREPEND puts it at the TOP of the menu so you can't miss it
            $menu.prepend( $newItem );
        }

        // 1. Run on load
        injectLink();

        // 2. Run whenever the drawer is opened (Click listener)
        // We listen on the document body for clicks on the hamburger icon
        $( 'body' ).on( 'click', '.mw-ui-icon-minerva-mainmenu, #mw-mf-main-menu-button', function() {
            // Retry multiple times as the menu slides in
            var count = 0;
            var interval = setInterval(function() {
                injectLink();
                count++;
                if (count > 20) clearInterval(interval); // Stop after 2 seconds
            }, 100);
        });

        // 3. MutationObserver (The Backup)
        // Watch for the drawer appearing in the DOM
        var observer = new MutationObserver(function(mutations) {
            injectLink();
        });
        
        // Start observing the body for added nodes
        observer.observe(document.body, { childList: true, subtree: true });
    } );
} );