Jump to content

MediaWiki:Mobile.js: Difference between revisions

From Insurer Brain
Content deleted Content added
No edit summary
Tag: Manual revert
No edit summary
Line 113: Line 113:
});
});


// Helpers — find collapsed parent section and its H2 heading/anchor
// Navigate and try to ensure mobile-collapsed sections are visible
function findCollapsedAncestor(el) {
list.addEventListener('click', function (e) {
// Newer MF markup: <section aria-expanded="false">…</section>
var a = e.target.closest('a');
var sec = el.closest && el.closest('section[aria-expanded="false"]');
if (!a) return;
if (sec) return { type: 'section', node: sec };
e.preventDefault();


// Older MF markup: content block with no .open-block; header is previous sibling
var targetId = a.getAttribute('href').slice(1);
var block = el.closest && el.closest('.collapsible-block');
var target = document.getElementById(targetId);
if (block && !block.classList.contains('open-block')) {
closeOverlay();
return { type: 'block', node: block };
}
return null;
}


function findSectionHeading(collapsed) {
if (target) {
if (!collapsed) return null;
try {
if (collapsed.type === 'section') {
target.scrollIntoView({ behavior: 'smooth', block: 'start' });
// Prefer the H2 in this section; fall back to any .section-heading
} catch (_) {
return collapsed.node.querySelector('h2.section-heading, h2, .section-heading');
target.scrollIntoView(true);
}
}
// .collapsible-block: heading toggle is the previous element
var prev = collapsed.node.previousElementSibling;
if (prev && (prev.matches('h2, .section-heading, .collapsible-heading'))) return prev;
return null;
}


function findAnchorForHeading(heading) {
// Update URL hash after a tick (so browser back works)
if (!heading) return null;
setTimeout(function () {
// In most wikis the anchor id lives on span.mw-headline (inside h2)
if (history && history.replaceState) {
var span = heading.querySelector && heading.querySelector('.mw-headline[id]');
history.replaceState(null, '', '#' + targetId);
if (span) return span;
} else {
// Otherwise the H2 itself may carry the id
location.hash = targetId;
return heading.id ? heading : null;
}
}
}, 200);


function scrollToElement(el) {
// MobileFrontend: headings may be inside collapsed sections.
try { el.scrollIntoView({ behavior: 'smooth', block: 'start' }); }
// Heuristic: click the nearest toggle if present.
catch (_) { el.scrollIntoView(true); }
var maybeToggle = target.closest('.collapsible-block, .mf-section') ||
}
target.closest('section');

if (maybeToggle && maybeToggle.classList.contains('collapsed')) {
// ⬇️ Replace your existing list click handler with this one
// Try to open; fallback by clicking the first heading inside
list.addEventListener('click', function (e) {
var headingToggle = maybeToggle.querySelector('.section-heading, h2, h3, h4, h5, h6');
var a = e.target && e.target.closest('a');
if (headingToggle) headingToggle.click();
if (!a) return;

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

// Determine the clicked level (we set this in <li data-level="…"> when building the list)
var li = a.closest('li');
var level = li ? parseInt(li.getAttribute('data-level') || '0', 10) : 0;

// If user tapped an H3+ and its H2 section is collapsed → go to that H2 instead
if (target && level >= 3) {
var collapsed = findCollapsedAncestor(target);
if (collapsed) {
var h2 = findSectionHeading(collapsed);
var anchorEl = findAnchorForHeading(h2) || h2;
if (anchorEl) {
scrollToElement(anchorEl);
// Update URL to the H2's anchor if available
if (anchorEl.id) {
setTimeout(function () {
if (history && history.replaceState) {
history.replaceState(null, '', '#' + anchorEl.id);
} else {
location.hash = anchorEl.id;
}
}, 200);
}
return; // done
}
}
}
}
});
}

// Default behavior: go to the requested target (H2 or H3) when not inside a collapsed section
if (target) {
scrollToElement(target);
setTimeout(function () {
if (history && history.replaceState) {
history.replaceState(null, '', '#' + targetId);
} else {
location.hash = targetId;
}
}, 200);
}
});


// Re-hide on rotation/resize to tablet/desktop
// Re-hide on rotation/resize to tablet/desktop

Revision as of 19:07, 17 October 2025

/* All JavaScript here will be loaded for users of the mobile site */
/* Note, there is no corresponding User:Username/mobile.js; however users may use User:Username/minerva.js */
function addPortletLink() {
  mw.log.warn('addPortletLink is deprecated on desktop and never implemented on mobile', 'More information on https://www.mediawiki.org/wiki/ResourceLoader/Migration_guide_(users)#addPortletLink');
}
// 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 isArticle = !!mw.config.get('wgIsArticle');
    if (!isArticle) 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 < 3) 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();
  });

// Helpers — find collapsed parent section and its H2 heading/anchor
function findCollapsedAncestor(el) {
  // Newer MF markup: <section aria-expanded="false">…</section>
  var sec = el.closest && el.closest('section[aria-expanded="false"]');
  if (sec) return { type: 'section', node: sec };

  // Older MF markup: content block with no .open-block; header is previous sibling
  var block = el.closest && el.closest('.collapsible-block');
  if (block && !block.classList.contains('open-block')) {
    return { type: 'block', node: block };
  }
  return null;
}

function findSectionHeading(collapsed) {
  if (!collapsed) return null;
  if (collapsed.type === 'section') {
    // Prefer the H2 in this section; fall back to any .section-heading
    return collapsed.node.querySelector('h2.section-heading, h2, .section-heading');
  }
  // .collapsible-block: heading toggle is the previous element
  var prev = collapsed.node.previousElementSibling;
  if (prev && (prev.matches('h2, .section-heading, .collapsible-heading'))) return prev;
  return null;
}

function findAnchorForHeading(heading) {
  if (!heading) return null;
  // In most wikis the anchor id lives on span.mw-headline (inside h2)
  var span = heading.querySelector && heading.querySelector('.mw-headline[id]');
  if (span) return span;
  // Otherwise the H2 itself may carry the id
  return heading.id ? heading : null;
}

function scrollToElement(el) {
  try { el.scrollIntoView({ behavior: 'smooth', block: 'start' }); }
  catch (_) { el.scrollIntoView(true); }
}

// ⬇️ Replace your existing list click handler with this one
list.addEventListener('click', function (e) {
  var a = e.target && e.target.closest('a');
  if (!a) return;

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

  // Determine the clicked level (we set this in <li data-level="…"> when building the list)
  var li = a.closest('li');
  var level = li ? parseInt(li.getAttribute('data-level') || '0', 10) : 0;

  // If user tapped an H3+ and its H2 section is collapsed → go to that H2 instead
  if (target && level >= 3) {
    var collapsed = findCollapsedAncestor(target);
    if (collapsed) {
      var h2 = findSectionHeading(collapsed);
      var anchorEl = findAnchorForHeading(h2) || h2;
      if (anchorEl) {
        scrollToElement(anchorEl);
        // Update URL to the H2's anchor if available
        if (anchorEl.id) {
          setTimeout(function () {
            if (history && history.replaceState) {
              history.replaceState(null, '', '#' + anchorEl.id);
            } else {
              location.hash = anchorEl.id;
            }
          }, 200);
        }
        return; // done
      }
    }
  }

  // Default behavior: go to the requested target (H2 or H3) when not inside a collapsed section
  if (target) {
    scrollToElement(target);
    setTimeout(function () {
      if (history && history.replaceState) {
        history.replaceState(null, '', '#' + targetId);
      } else {
        location.hash = targetId;
      }
    }, 200);
  }
});

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