MediaWiki:Mobile.js: Difference between revisions
Appearance
Content deleted Content added
No edit summary |
No edit summary Tag: Reverted |
||
| Line 1: | Line 1: | ||
/* All JavaScript here will be loaded for users of the mobile site */ |
|||
// CapSach — Mobile TOC overlay (all skins; phone widths) |
|||
/* 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 () { |
(function () { |
||
// --- utilities ------------------------------------------------------------- |
|||
// Don’t run on very wide screens (tablet/desktop have native TOC) |
|||
function isMobileSite() { |
|||
if (window.matchMedia('(min-width: 768px)').matches) return; |
|||
// Stable MobileFrontend signal on <body>; documented as safe to use by gadgets |
|||
// (prefer this over wgMFMode for compatibility). |
|||
return document.body && document.body.classList.contains('mw-mf'); |
|||
} |
|||
// guard against duplicate UI across SPA-like re-renders |
|||
function notAlready(id) { return !document.getElementById(id); } |
|||
function onReady(fn) { |
|||
// Only on normal content pages |
|||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', fn); |
|||
if (window.mw && mw.config && mw.config.get) { |
|||
else fn(); |
|||
var isArticle = !!mw.config.get('wgIsArticle'); |
|||
if (!isArticle) return; |
|||
} |
} |
||
function getContentRoot() { |
|||
// Find the content root; MobileFrontend restructures DOM, so be flexible |
|||
return ( |
|||
document.querySelector('#mw-content-text .mw-parser-output') || |
document.querySelector('#mw-content-text .mw-parser-output') || |
||
document.querySelector('.mw-parser-output') || |
document.querySelector('.mw-parser-output') || |
||
document.getElementById('mw-content-text') || |
document.getElementById('mw-content-text') || |
||
document.querySelector('#content') || |
document.querySelector('#content') || |
||
document.body |
document.body |
||
); |
|||
} |
|||
function smoothScrollTo(el) { |
|||
// Collect headings (H2–H6). Prefer spans with .mw-headline (stable anchor ids) |
|||
// Adjust for sticky headers (Minerva/other mobile skins). We detect any fixed/sticky element |
|||
var items = []; |
|||
// touching the top edge and subtract its bottom coordinate. |
|||
var headings = root.querySelectorAll('h2, h3, h4, h5, h6'); |
|||
var offset = 0; |
|||
headings.forEach(function (h) { |
|||
try { |
|||
var level = parseInt(h.tagName.slice(1), 10); |
|||
var candidates = document.querySelectorAll('header, .minerva-header, .mw-header, .site-header, #header, .header'); |
|||
if (level < 2 || level > 6) return; |
|||
candidates.forEach(function (node) { |
|||
var headline = h.querySelector('.mw-headline') || h; |
|||
var cs = window.getComputedStyle(node); |
|||
var id = headline.id || h.id; |
|||
if (cs.position === 'fixed' || cs.position === 'sticky') { |
|||
var r = node.getBoundingClientRect(); |
|||
if (!id || !text) return; |
|||
if (r.top <= 0 && r.bottom > 0) offset = Math.max(offset, r.bottom); |
|||
items.push({ id: id, text: text, level: level }); |
|||
} |
} |
||
}); |
|||
} catch (_) {} |
|||
var y = el.getBoundingClientRect().top + window.pageYOffset - Math.max(0, Math.floor(offset)); |
|||
try { window.scrollTo({ top: y, behavior: 'smooth' }); } catch (_) { window.scrollTo(0, y); } |
|||
} |
|||
// Given an <h2>, find the thing that actually toggles it on the mobile site. |
|||
// Show only if there are enough headings to be useful (match core default) |
|||
// Per MF’s accessibility work, the control exposes aria-expanded (on the heading |
|||
if (items.length < 3) return; |
|||
// or on a descendant like .mw-headline). :contentReference[oaicite:1]{index=1} |
|||
function getH2Toggle(h2El) { |
|||
if (!h2El) return null; |
|||
// Preferred: a descendant with both aria-controls and aria-expanded |
|||
var ctrl = h2El.querySelector('[aria-controls][aria-expanded]'); |
|||
if (ctrl) return ctrl; |
|||
// Next best: any descendant with aria-expanded |
|||
ctrl = h2El.querySelector('[aria-expanded]'); |
|||
if (ctrl) return ctrl; |
|||
// Legacy: the H2 itself is the toggle |
|||
if (h2El.hasAttribute('aria-expanded') || h2El.classList.contains('section-heading') || |
|||
h2El.classList.contains('collapsible-heading')) { |
|||
return h2El; |
|||
} |
|||
return null; |
|||
} |
|||
// Determine if an H2 is collapsed by reading aria-expanded (preferred), |
|||
// Create trigger button (bottom-left; avoids “Back to top” on bottom-right) |
|||
// or by inspecting its controlled block (legacy .collapsible-block markup). |
|||
var btn = document.createElement('button'); |
|||
function h2IsCollapsed(h2El) { |
|||
btn.id = 'cps-open-toc'; |
|||
if (!h2El) return false; |
|||
btn.type = 'button'; |
|||
var toggle = getH2Toggle(h2El); |
|||
btn.setAttribute('aria-label', 'Open table of contents'); |
|||
if (toggle) { |
|||
btn.innerHTML = '<span class="icon" aria-hidden="true">≡</span><span class="label">TOC</span>'; |
|||
var ae = toggle.getAttribute('aria-expanded'); |
|||
document.body.appendChild(btn); |
|||
if (ae === 'false') return true; |
|||
if (ae === 'true') return false; |
|||
var controlsId = toggle.getAttribute('aria-controls'); |
|||
if (controlsId) { |
|||
var block = document.getElementById(controlsId); |
|||
if (block) { |
|||
if (block.hidden || block.getAttribute('hidden') !== null) return true; |
|||
if (block.classList.contains('collapsible-block') && !block.classList.contains('open-block')) return true; |
|||
} |
|||
} |
|||
} |
|||
// Fallback to sibling legacy block |
|||
var next = h2El.nextElementSibling; |
|||
if (next && next.classList.contains('collapsible-block')) { |
|||
return !next.classList.contains('open-block'); |
|||
} |
|||
return false; |
|||
} |
|||
// Open the H2 section if it’s collapsed; call cb when open (observer + timeout). |
|||
// Overlay + panel |
|||
function ensureH2Open(h2El, cb) { |
|||
var overlay = document.createElement('div'); |
|||
var toggle = getH2Toggle(h2El); |
|||
overlay.id = 'cps-toc-overlay'; |
|||
if (!toggle) { cb(); return; } |
|||
overlay.setAttribute('aria-hidden', 'true'); |
|||
var |
var alreadyOpen = !h2IsCollapsed(h2El); |
||
if (alreadyOpen) { cb(); return; } |
|||
panel.id = 'cps-toc-panel'; |
|||
panel.setAttribute('role', 'dialog'); |
|||
panel.setAttribute('aria-modal', 'true'); |
|||
panel.setAttribute('aria-label', 'Table of contents'); |
|||
var |
var done = false; |
||
function finish() { if (!done) { done = true; cb(); } } |
|||
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>'; |
|||
// Observe aria-expanded or class changes |
|||
var list = document.createElement('ul'); |
|||
var obs; |
|||
list.id = 'cps-toc-list'; |
|||
if (window.MutationObserver) { |
|||
obs = new MutationObserver(function () { |
|||
if (!h2IsCollapsed(h2El)) { |
|||
if (obs) obs.disconnect(); |
|||
finish(); |
|||
} |
|||
}); |
|||
// Watch both the toggle and its controlled content (if any) |
|||
var controlsId = toggle.getAttribute('aria-controls'); |
|||
var ctrlEl = controlsId ? document.getElementById(controlsId) : null; |
|||
var targets = [ toggle ]; |
|||
if (ctrlEl) targets.push(ctrlEl); |
|||
targets.forEach(function (t) { |
|||
obs.observe(t, { attributes: true, attributeFilter: ['aria-expanded', 'class', 'hidden'] }); |
|||
}); |
|||
} |
|||
// Click to open; MF exposes the toggle control (button/span) with aria-expanded. :contentReference[oaicite:2]{index=2} |
|||
items.forEach(function (it) { |
|||
try { |
|||
var li = document.createElement('li'); |
|||
toggle.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window })); |
|||
li.setAttribute('data-level', String(it.level)); |
|||
} catch (_) { |
|||
var a = document.createElement('a'); |
|||
toggle.click(); |
|||
} |
|||
a.textContent = it.text; |
|||
li.appendChild(a); |
|||
list.appendChild(li); |
|||
}); |
|||
// Safety fallback in case MutationObserver doesn’t fire |
|||
panel.appendChild(header); |
|||
setTimeout(function () { |
|||
panel.appendChild(list); |
|||
if (obs) obs.disconnect(); |
|||
overlay.appendChild(panel); |
|||
finish(); |
|||
document.body.appendChild(overlay); |
|||
}, 600); |
|||
} |
|||
// Get the anchor element for any heading element (h2..h6) across old/new markup. :contentReference[oaicite:3]{index=3} |
|||
// Focus handling |
|||
function anchorForHeadingEl(hEl) { |
|||
var lastFocus = null; |
|||
if (!hEl) return null; |
|||
function openOverlay() { |
|||
var span = hEl.querySelector && hEl.querySelector('.mw-headline[id]'); |
|||
lastFocus = document.activeElement; |
|||
if (span) return span; |
|||
overlay.classList.add('is-open'); |
|||
return hEl.id ? hEl : null; |
|||
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 }); |
|||
} |
} |
||
// --- main initializer ------------------------------------------------------ |
|||
btn.style.display = 'flex'; // reveal trigger now that we know we have headings |
|||
function initTOC() { |
|||
btn.addEventListener('click', openOverlay); |
|||
// Phones only; larger viewports keep native TOC |
|||
if (window.matchMedia('(min-width: 768px)').matches) return; |
|||
// Only on normal content pages |
|||
overlay.addEventListener('click', function (e) { |
|||
if (mw.config && !mw.config.get('wgIsArticle')) return; |
|||
// Click outside the bottom sheet closes |
|||
if (e.target === overlay) closeOverlay(); |
|||
}); |
|||
overlay.querySelector('#cps-toc-close').addEventListener('click', closeOverlay); |
|||
// Avoid duplicate widgets after SPA-like content swaps |
|||
overlay.addEventListener('keydown', function (e) { |
|||
if ( |
if (!notAlready('cps-open-toc')) return; |
||
}); |
|||
var root = getContentRoot(); |
|||
// 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(); |
|||
// Build a flat list of headings and a quick index by id |
|||
var targetId = a.getAttribute('href').slice(1); |
|||
var |
var items = []; |
||
var indexById = Object.create(null); |
|||
closeOverlay(); |
|||
var headingElById = Object.create(null); |
|||
var headings = root.querySelectorAll('h2, h3, h4, h5, h6'); |
|||
if (target) { |
|||
headings.forEach(function (h) { |
|||
try { |
|||
var level = parseInt(h.tagName.slice(1), 10); |
|||
target.scrollIntoView({ behavior: 'smooth', block: 'start' }); |
|||
if (level < 2 || level > 6) return; |
|||
// IDs may be on the Hn or on .mw-headline depending on MW version |
|||
target.scrollIntoView(true); |
|||
var candidate = h.querySelector('.mw-headline[id]') || h; |
|||
} |
|||
var id = candidate.id || h.id; |
|||
var text = (candidate.textContent || h.textContent || '').trim(); |
|||
if (!id || !text) return; |
|||
items.push({ id: id, text: text, level: level }); |
|||
// Update URL hash after a tick (so browser back works) |
|||
indexById[id] = items.length - 1; |
|||
setTimeout(function () { |
|||
headingElById[id] = h; |
|||
if (history && history.replaceState) { |
|||
}); |
|||
history.replaceState(null, '', '#' + targetId); |
|||
} else { |
|||
location.hash = targetId; |
|||
} |
|||
}, 200); |
|||
if (items.length < 3) return; // mirror core TOC threshold |
|||
// MobileFrontend: headings may be inside collapsed sections. |
|||
// Heuristic: click the nearest toggle if present. |
|||
// UI: trigger button |
|||
var maybeToggle = target.closest('.collapsible-block, .mf-section') || |
|||
var btn = document.createElement('button'); |
|||
btn.id = 'cps-open-toc'; |
|||
if (maybeToggle && maybeToggle.classList.contains('collapsed')) { |
|||
btn.type = 'button'; |
|||
// Try to open; fallback by clicking the first heading inside |
|||
btn.setAttribute('aria-label', 'Open table of contents'); |
|||
var headingToggle = maybeToggle.querySelector('.section-heading, h2, h3, h4, h5, h6'); |
|||
btn.innerHTML = '<span class="icon" aria-hidden="true">≡</span><span class="label">TOC</span>'; |
|||
if (headingToggle) headingToggle.click(); |
|||
document.body.appendChild(btn); |
|||
} |
|||
// UI: 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 + open/close |
|||
var lastFocus = null; |
|||
function openOverlay() { |
|||
lastFocus = document.activeElement; |
|||
overlay.classList.add('is-open'); |
|||
overlay.setAttribute('aria-hidden', 'false'); |
|||
document.body.style.overflow = 'hidden'; |
|||
var first = list.querySelector('a'); |
|||
if (first) first.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'; |
|||
// Re-hide on rotation/resize to tablet/desktop |
|||
btn.addEventListener('click', openOverlay); |
|||
overlay.addEventListener('click', function (e) { if (e.target === overlay) closeOverlay(); }); |
|||
if (window.matchMedia('(min-width: 768px)').matches) { |
|||
overlay.querySelector('#cps-toc-close').addEventListener('click', closeOverlay); |
|||
btn.style.display = 'none'; |
|||
closeOverlay(); |
overlay.addEventListener('keydown', function (e) { if (e.key === 'Escape') closeOverlay(); }); |
||
} else { |
|||
// Helper: find the nearest preceding H2 for any given id |
|||
btn.style.display = 'flex'; |
|||
function parentH2For(id) { |
|||
var idx = indexById[id]; |
|||
if (typeof idx !== 'number') return null; |
|||
for (var i = idx - 1; i >= 0; i--) if (items[i].level === 2) return items[i]; |
|||
return null; |
|||
} |
} |
||
}, { passive: true }); |
|||
// NAVIGATION: open parent H2 if needed, then scroll to target |
|||
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 li = a.closest('li'); |
|||
var level = li ? parseInt(li.getAttribute('data-level') || '0', 10) : 0; |
|||
var targetEl = document.getElementById(targetId); |
|||
// close sheet first, then navigate (let layout settle for iOS) |
|||
closeOverlay(); |
|||
// If H3+ and parent H2 exists, ensure it is open first |
|||
if (level >= 3) { |
|||
var p = parentH2For(targetId); |
|||
if (p) { |
|||
var h2El = headingElById[p.id]; |
|||
ensureH2Open(h2El, function () { |
|||
// after open, try the target; if missing/blocked, route to H2 anchor |
|||
var preferred = document.getElementById(targetId); |
|||
var finalEl = preferred || anchorForHeadingEl(h2El) || h2El; |
|||
if (!finalEl) return; |
|||
// Use rAF so we scroll after any reflow caused by opening |
|||
requestAnimationFrame(function () { |
|||
smoothScrollTo(finalEl); |
|||
// Update hash to the element we actually scrolled to |
|||
var finalId = finalEl.id || targetId; |
|||
setTimeout(function () { |
|||
if (history && history.replaceState) history.replaceState(null, '', '#' + finalId); |
|||
else location.hash = finalId; |
|||
}, 150); |
|||
}); |
|||
}); |
|||
return; |
|||
} |
|||
} |
|||
// H2 or no parent found: just go to the target we have |
|||
var dest = targetEl || (level === 2 ? anchorForHeadingEl(headingElById[targetId]) : null); |
|||
if (!dest) return; |
|||
requestAnimationFrame(function () { |
|||
smoothScrollTo(dest); |
|||
setTimeout(function () { |
|||
if (history && history.replaceState) history.replaceState(null, '', '#' + (dest.id || targetId)); |
|||
else location.hash = dest.id || targetId; |
|||
}, 150); |
|||
}); |
|||
}); |
|||
// Hide/show trigger on rotation |
|||
window.addEventListener('resize', function () { |
|||
if (window.matchMedia('(min-width: 768px)').matches) { btn.style.display = 'none'; closeOverlay(); } |
|||
else { btn.style.display = 'flex'; } |
|||
}, { passive: true }); |
|||
} |
|||
// --- bootstrap: wait for MobileFrontend then initialise -------------------- |
|||
if (window.mw && mw.loader) { |
|||
// Ensure MF client-side bits are present (toggle, section markup, etc.) :contentReference[oaicite:4]{index=4} |
|||
mw.loader.using('mobile.startup').then(function () { |
|||
onReady(function () { if (isMobileSite()) initTOC(); }); |
|||
if (mw.hook) mw.hook('wikipage.content').add(function () { if (isMobileSite()) initTOC(); }); |
|||
}); |
|||
} else { |
|||
// Extremely defensive fallback |
|||
onReady(function () { if (isMobileSite()) initTOC(); }); |
|||
} |
|||
})(); |
})(); |
||
Revision as of 22:03, 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 () {
// --- utilities -------------------------------------------------------------
function isMobileSite() {
// Stable MobileFrontend signal on <body>; documented as safe to use by gadgets
// (prefer this over wgMFMode for compatibility).
return document.body && document.body.classList.contains('mw-mf');
}
// guard against duplicate UI across SPA-like re-renders
function notAlready(id) { return !document.getElementById(id); }
function onReady(fn) {
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', fn);
else fn();
}
function getContentRoot() {
return (
document.querySelector('#mw-content-text .mw-parser-output') ||
document.querySelector('.mw-parser-output') ||
document.getElementById('mw-content-text') ||
document.querySelector('#content') ||
document.body
);
}
function smoothScrollTo(el) {
// Adjust for sticky headers (Minerva/other mobile skins). We detect any fixed/sticky element
// touching the top edge and subtract its bottom coordinate.
var offset = 0;
try {
var candidates = document.querySelectorAll('header, .minerva-header, .mw-header, .site-header, #header, .header');
candidates.forEach(function (node) {
var cs = window.getComputedStyle(node);
if (cs.position === 'fixed' || cs.position === 'sticky') {
var r = node.getBoundingClientRect();
if (r.top <= 0 && r.bottom > 0) offset = Math.max(offset, r.bottom);
}
});
} catch (_) {}
var y = el.getBoundingClientRect().top + window.pageYOffset - Math.max(0, Math.floor(offset));
try { window.scrollTo({ top: y, behavior: 'smooth' }); } catch (_) { window.scrollTo(0, y); }
}
// Given an <h2>, find the thing that actually toggles it on the mobile site.
// Per MF’s accessibility work, the control exposes aria-expanded (on the heading
// or on a descendant like .mw-headline). :contentReference[oaicite:1]{index=1}
function getH2Toggle(h2El) {
if (!h2El) return null;
// Preferred: a descendant with both aria-controls and aria-expanded
var ctrl = h2El.querySelector('[aria-controls][aria-expanded]');
if (ctrl) return ctrl;
// Next best: any descendant with aria-expanded
ctrl = h2El.querySelector('[aria-expanded]');
if (ctrl) return ctrl;
// Legacy: the H2 itself is the toggle
if (h2El.hasAttribute('aria-expanded') || h2El.classList.contains('section-heading') ||
h2El.classList.contains('collapsible-heading')) {
return h2El;
}
return null;
}
// Determine if an H2 is collapsed by reading aria-expanded (preferred),
// or by inspecting its controlled block (legacy .collapsible-block markup).
function h2IsCollapsed(h2El) {
if (!h2El) return false;
var toggle = getH2Toggle(h2El);
if (toggle) {
var ae = toggle.getAttribute('aria-expanded');
if (ae === 'false') return true;
if (ae === 'true') return false;
var controlsId = toggle.getAttribute('aria-controls');
if (controlsId) {
var block = document.getElementById(controlsId);
if (block) {
if (block.hidden || block.getAttribute('hidden') !== null) return true;
if (block.classList.contains('collapsible-block') && !block.classList.contains('open-block')) return true;
}
}
}
// Fallback to sibling legacy block
var next = h2El.nextElementSibling;
if (next && next.classList.contains('collapsible-block')) {
return !next.classList.contains('open-block');
}
return false;
}
// Open the H2 section if it’s collapsed; call cb when open (observer + timeout).
function ensureH2Open(h2El, cb) {
var toggle = getH2Toggle(h2El);
if (!toggle) { cb(); return; }
var alreadyOpen = !h2IsCollapsed(h2El);
if (alreadyOpen) { cb(); return; }
var done = false;
function finish() { if (!done) { done = true; cb(); } }
// Observe aria-expanded or class changes
var obs;
if (window.MutationObserver) {
obs = new MutationObserver(function () {
if (!h2IsCollapsed(h2El)) {
if (obs) obs.disconnect();
finish();
}
});
// Watch both the toggle and its controlled content (if any)
var controlsId = toggle.getAttribute('aria-controls');
var ctrlEl = controlsId ? document.getElementById(controlsId) : null;
var targets = [ toggle ];
if (ctrlEl) targets.push(ctrlEl);
targets.forEach(function (t) {
obs.observe(t, { attributes: true, attributeFilter: ['aria-expanded', 'class', 'hidden'] });
});
}
// Click to open; MF exposes the toggle control (button/span) with aria-expanded. :contentReference[oaicite:2]{index=2}
try {
toggle.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
} catch (_) {
toggle.click();
}
// Safety fallback in case MutationObserver doesn’t fire
setTimeout(function () {
if (obs) obs.disconnect();
finish();
}, 600);
}
// Get the anchor element for any heading element (h2..h6) across old/new markup. :contentReference[oaicite:3]{index=3}
function anchorForHeadingEl(hEl) {
if (!hEl) return null;
var span = hEl.querySelector && hEl.querySelector('.mw-headline[id]');
if (span) return span;
return hEl.id ? hEl : null;
}
// --- main initializer ------------------------------------------------------
function initTOC() {
// Phones only; larger viewports keep native TOC
if (window.matchMedia('(min-width: 768px)').matches) return;
// Only on normal content pages
if (mw.config && !mw.config.get('wgIsArticle')) return;
// Avoid duplicate widgets after SPA-like content swaps
if (!notAlready('cps-open-toc')) return;
var root = getContentRoot();
// Build a flat list of headings and a quick index by id
var items = [];
var indexById = Object.create(null);
var headingElById = Object.create(null);
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;
// IDs may be on the Hn or on .mw-headline depending on MW version
var candidate = h.querySelector('.mw-headline[id]') || h;
var id = candidate.id || h.id;
var text = (candidate.textContent || h.textContent || '').trim();
if (!id || !text) return;
items.push({ id: id, text: text, level: level });
indexById[id] = items.length - 1;
headingElById[id] = h;
});
if (items.length < 3) return; // mirror core TOC threshold
// UI: trigger button
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);
// UI: 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 + open/close
var lastFocus = null;
function openOverlay() {
lastFocus = document.activeElement;
overlay.classList.add('is-open');
overlay.setAttribute('aria-hidden', 'false');
document.body.style.overflow = 'hidden';
var first = list.querySelector('a');
if (first) first.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';
btn.addEventListener('click', openOverlay);
overlay.addEventListener('click', function (e) { if (e.target === overlay) closeOverlay(); });
overlay.querySelector('#cps-toc-close').addEventListener('click', closeOverlay);
overlay.addEventListener('keydown', function (e) { if (e.key === 'Escape') closeOverlay(); });
// Helper: find the nearest preceding H2 for any given id
function parentH2For(id) {
var idx = indexById[id];
if (typeof idx !== 'number') return null;
for (var i = idx - 1; i >= 0; i--) if (items[i].level === 2) return items[i];
return null;
}
// NAVIGATION: open parent H2 if needed, then scroll to target
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 li = a.closest('li');
var level = li ? parseInt(li.getAttribute('data-level') || '0', 10) : 0;
var targetEl = document.getElementById(targetId);
// close sheet first, then navigate (let layout settle for iOS)
closeOverlay();
// If H3+ and parent H2 exists, ensure it is open first
if (level >= 3) {
var p = parentH2For(targetId);
if (p) {
var h2El = headingElById[p.id];
ensureH2Open(h2El, function () {
// after open, try the target; if missing/blocked, route to H2 anchor
var preferred = document.getElementById(targetId);
var finalEl = preferred || anchorForHeadingEl(h2El) || h2El;
if (!finalEl) return;
// Use rAF so we scroll after any reflow caused by opening
requestAnimationFrame(function () {
smoothScrollTo(finalEl);
// Update hash to the element we actually scrolled to
var finalId = finalEl.id || targetId;
setTimeout(function () {
if (history && history.replaceState) history.replaceState(null, '', '#' + finalId);
else location.hash = finalId;
}, 150);
});
});
return;
}
}
// H2 or no parent found: just go to the target we have
var dest = targetEl || (level === 2 ? anchorForHeadingEl(headingElById[targetId]) : null);
if (!dest) return;
requestAnimationFrame(function () {
smoothScrollTo(dest);
setTimeout(function () {
if (history && history.replaceState) history.replaceState(null, '', '#' + (dest.id || targetId));
else location.hash = dest.id || targetId;
}, 150);
});
});
// Hide/show trigger on rotation
window.addEventListener('resize', function () {
if (window.matchMedia('(min-width: 768px)').matches) { btn.style.display = 'none'; closeOverlay(); }
else { btn.style.display = 'flex'; }
}, { passive: true });
}
// --- bootstrap: wait for MobileFrontend then initialise --------------------
if (window.mw && mw.loader) {
// Ensure MF client-side bits are present (toggle, section markup, etc.) :contentReference[oaicite:4]{index=4}
mw.loader.using('mobile.startup').then(function () {
onReady(function () { if (isMobileSite()) initTOC(); });
if (mw.hook) mw.hook('wikipage.content').add(function () { if (isMobileSite()) initTOC(); });
});
} else {
// Extremely defensive fallback
onReady(function () { if (isMobileSite()) initTOC(); });
}
})();