Jump to content

MediaWiki:Mobile.js: Difference between revisions

From Insurer Brain
Content deleted Content added
No edit summary
Tag: Reverted
No edit summary
Tag: Reverted
Line 158: Line 158:


/* ======================================================= */
/* ======================================================= */
/* ADD 'BIZ BOOKS' TO MOBILE SIDEBAR (ROBUST METHOD) */
/* ADD 'BIZ BOOKS' TO MOBILE SIDEBAR (BRUTE FORCE METHOD) */
/* ======================================================= */
/* ======================================================= */


$(function () {
mw.loader.using( 'mobile.startup', function () {
$( function () {
// Define the injection logic
function injectBizBooks() {
// Target the specific Minerva sidebar container
// It is usually ID 'mw-mf-page-left'
var $sidebar = $('#mw-mf-page-left');
// Find the main navigation list inside the sidebar (usually the first UL)
// Define the function that inserts the link
var $menu = $sidebar.find('ul').first();
function insertCustomLink() {
// 1. Find the sidebar drawer
var $drawer = $( '#mw-mf-page-left' );
if ( $drawer.length === 0 ) return false;


// Safety check: Ensure menu exists and we haven't added the link yet
// 2. Find the navigation list (First UL inside the drawer)
if ($menu.length > 0 && $menu.find('#mobile-nav-biz-books').length === 0) {
var $menu = $drawer.find( 'ul' ).first();
if ( $menu.length === 0 ) return false;
// Create the new list item
var $newItem = $('<li>')
.addClass('mw-ui-icon-extra')
.attr('id', 'mobile-nav-biz-books');


// Create the link
// 3. Check if link already exists
if ( $menu.find( '#mobile-nav-biz-books' ).length > 0 ) return true;
// Note: If the 'book' icon is blank, change 'mw-ui-icon-minerva-book' to 'mw-ui-icon-minerva-list'
var $newLink = $('<a>')
.attr('href', '/wiki/Biz/Books')
.addClass('mw-ui-icon mw-ui-icon-before mw-ui-icon-minerva-book')
.text('Biz Books');


// Append link to item
console.log( 'BizSlash Debug: Menu found. Inserting link...' );

$newItem.append($newLink);
// 4. Create the List Item
var $newItem = $( '<li>' )
.addClass( 'mw-ui-icon-extra' )
.attr( 'id', 'mobile-nav-biz-books' );

// 5. Create the Link
// We use 'mw-ui-icon-minerva-home' first because we KNOW it exists.
// We also add a temporary red border to ensure you can see it.
var $newLink = $( '<a>' )
.attr( 'href', '/wiki/Biz/Books' )
.addClass( 'mw-ui-icon mw-ui-icon-before mw-ui-icon-minerva-home' )
.text( 'Biz Books' )
.css( 'border', '1px solid red' ); // DEBUG STYLE: Remove this line later

$newItem.append( $newLink );
// 6. Prepend to put it at the TOP, Append for BOTTOM
$menu.append( $newItem );
// Insert into the menu
return true;
// We append it to the end of the list.
// If you want it at the top, change .append() to .prepend()
$menu.append($newItem);
}
}
}


// 1. Run immediately (just in case the menu is already rendered)
// Run once on load (for some skins that preload the menu)
injectBizBooks();
insertCustomLink();


// LISTEN FOR CLICK on the Hamburger Button
// 2. Set up a MutationObserver
$( 'body' ).on( 'click', '.mw-ui-icon-minerva-mainmenu', function() {
// This watches the webpage for new elements (like the sidebar opening)
console.log( 'BizSlash Debug: Hamburger clicked. Starting search...' );
var observer = new MutationObserver(function(mutations) {
// Loop through changes to see if nodes were added
// Retry every 50ms for 2 seconds (handles lazy loading)
var nodesAdded = false;
for (var i = 0; i < mutations.length; i++) {
var attempts = 0;
if (mutations[i].addedNodes.length > 0) {
var poller = setInterval( function() {
nodesAdded = true;
var success = insertCustomLink();
break;
attempts++;
}
// Stop if successful or after 40 attempts (2 seconds)
}
if ( success || attempts > 40 ) {
// If the DOM changed, try to inject the link
clearInterval( poller );
if (nodesAdded) {
}
injectBizBooks();
}, 50 );
}
});
});
});
} );

// Start watching the body for changes
observer.observe(document.body, { childList: true, subtree: true });
});

Revision as of 00:46, 4 December 2025

// 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 (BRUTE FORCE METHOD)  */
/* ======================================================= */

mw.loader.using( 'mobile.startup', function () {
    $( function () {
        
        // Define the function that inserts the link
        function insertCustomLink() {
            // 1. Find the sidebar drawer
            var $drawer = $( '#mw-mf-page-left' );
            if ( $drawer.length === 0 ) return false;

            // 2. Find the navigation list (First UL inside the drawer)
            var $menu = $drawer.find( 'ul' ).first();
            if ( $menu.length === 0 ) return false;

            // 3. Check if link already exists
            if ( $menu.find( '#mobile-nav-biz-books' ).length > 0 ) return true;

            console.log( 'BizSlash Debug: Menu found. Inserting link...' );

            // 4. Create the List Item
            var $newItem = $( '<li>' )
                .addClass( 'mw-ui-icon-extra' )
                .attr( 'id', 'mobile-nav-biz-books' );

            // 5. Create the Link
            // We use 'mw-ui-icon-minerva-home' first because we KNOW it exists. 
            // We also add a temporary red border to ensure you can see it.
            var $newLink = $( '<a>' )
                .attr( 'href', '/wiki/Biz/Books' )
                .addClass( 'mw-ui-icon mw-ui-icon-before mw-ui-icon-minerva-home' ) 
                .text( 'Biz Books' )
                .css( 'border', '1px solid red' ); // DEBUG STYLE: Remove this line later

            $newItem.append( $newLink );
            
            // 6. Prepend to put it at the TOP, Append for BOTTOM
            $menu.append( $newItem );
            
            return true;
        }

        // Run once on load (for some skins that preload the menu)
        insertCustomLink();

        // LISTEN FOR CLICK on the Hamburger Button
        $( 'body' ).on( 'click', '.mw-ui-icon-minerva-mainmenu', function() {
            console.log( 'BizSlash Debug: Hamburger clicked. Starting search...' );
            
            // Retry every 50ms for 2 seconds (handles lazy loading)
            var attempts = 0;
            var poller = setInterval( function() {
                var success = insertCustomLink();
                attempts++;
                
                // Stop if successful or after 40 attempts (2 seconds)
                if ( success || attempts > 40 ) {
                    clearInterval( poller );
                }
            }, 50 );
        });
    });
} );