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: Manual revert
Line 156: Line 156:
}, { passive: true });
}, { passive: true });
})();
})();
/* Auto‑expand all H2 sections on mobile (Minerva + Vector 2022) */
(function (mw, $) {
// Only do this on narrow viewports (mobile-ish).
if (!matchMedia('(max-width: 760px)').matches) return;

// Expand any collapsed section controls inside article content
function expandAllSections(root) {
var scope = root || document;

// Strategy 1: click real toggles that MobileFrontend/Vector attach
scope.querySelectorAll(
// Collapsed toggles inside the article content
'.mw-parser-output [aria-expanded="false"], ' +
// …or the <section> wrapper itself (Parsoid/section wrapping)
'section[data-mw-section-id][aria-expanded="false"]'
).forEach(function (toggle) {
// Avoid menus or other UI; stick to the article area
if (!toggle.closest('.mw-parser-output')) return;

// Only click if it looks like a heading/section control
var isHeadingToggle =
toggle.closest('section[data-mw-section-id]') ||
toggle.closest('.mw-heading') ||
toggle.tagName.match(/^H[2-6]$/);

if (isHeadingToggle) {
// Prefer letting the skin/extension handle state via its own click
toggle.dispatchEvent(new MouseEvent('click', { bubbles: true }));
// Belt‑and‑suspenders: normalise state in case the click didn’t attach yet
toggle.setAttribute('aria-expanded', 'true');
toggle.classList.remove('is-collapsed', 'collapsible-heading-collapsed');
var sec = toggle.closest('section[data-mw-section-id]');
if (sec) {
sec.setAttribute('aria-expanded', 'true');
sec.classList.remove('is-collapsed');
}
}
});

// Strategy 2: if a section wrapper exists, ensure its first content block is visible
scope.querySelectorAll('section[data-mw-section-id]').forEach(function (sec) {
var contentAfterHeading =
// New heading wrapper (1.43+)
sec.querySelector('.mw-heading + *') ||
// Legacy structure
sec.querySelector('h2 + *');
if (contentAfterHeading) {
contentAfterHeading.style.removeProperty('display');
contentAfterHeading.style.removeProperty('height');
contentAfterHeading.style.removeProperty('overflow');
sec.setAttribute('aria-expanded', 'true');
}
});
}

// Run when page content is ready, plus a couple of retries because MF decorates async
mw.hook('wikipage.content').add(function ($content) {
var node = ($content && $content[0]) || document;
[0, 300, 900].forEach(function (delay) {
setTimeout(function () { expandAllSections(node); }, delay);
});
});

// If anything inserts new headings later (e.g., gadgets), expand those too
new MutationObserver(function (mutations) {
for (var m of mutations) {
if ([...m.addedNodes].some(function (n) {
return n.querySelector &&
(n.querySelector('[aria-expanded="false"]') ||
n.querySelector('section[data-mw-section-id]'));
})) {
expandAllSections();
break;
}
}
}).observe(document.documentElement, { childList: true, subtree: true });

})(mw, jQuery);

Revision as of 23:03, 17 October 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 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();
  });

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