MediaWiki:Mobile.js: Difference between revisions
Appearance
Content deleted Content added
No edit summary Tag: Reverted |
No edit summary Tag: Reverted |
||
| Line 8: | Line 8: | ||
} |
} |
||
/* CapSach — Mobile TOC overlay (phones); |
/* CapSach — Mobile TOC overlay (phones); ALWAYS open parent H2 before scrolling to H3+ */ |
||
(function () { |
(function () { |
||
/* ---------- utilities ---------- */ |
/* ---------------- utilities ---------------- */ |
||
function isMobileSite() { |
function isMobileSite() { |
||
// Stable |
// Stable MF signal on <body> for gadgets/scripts. |
||
return document.body && document.body.classList.contains('mw-mf'); / |
return document.body && document.body.classList.contains('mw-mf'); // MobileFrontend active. :contentReference[oaicite:1]{index=1} |
||
} |
} |
||
function once(id) { return !document.getElementById(id); } |
function once(id) { return !document.getElementById(id); } |
||
function onReady(fn) { if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', fn); else fn(); } |
|||
function onReady(fn) { |
|||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', fn); |
|||
else fn(); |
|||
} |
|||
function getContentRoot() { |
function getContentRoot() { |
||
| Line 33: | Line 28: | ||
} |
} |
||
// |
// Scroll while compensating for any sticky headers in mobile skins. |
||
function smoothScrollTo(el) { |
function smoothScrollTo(el) { |
||
var offset = 0; |
var offset = 0; |
||
try { |
try { |
||
document.querySelectorAll('header, .minerva-header, .mw-header, .site-header, #header, .header').forEach(function (node) { |
|||
fixed.forEach(function (node) { |
|||
var cs = getComputedStyle(node); |
var cs = getComputedStyle(node); |
||
if (cs.position === 'fixed' || cs.position === 'sticky') { |
if (cs.position === 'fixed' || cs.position === 'sticky') { |
||
| Line 50: | Line 44: | ||
} |
} |
||
// In MW 1.43+ IDs may be on .mw-headline (inside the heading wrapper). :contentReference[oaicite:2]{index=2} |
|||
/* ---------- MF section helpers ---------- */ |
|||
// NEW heading markup: ids can be on <hN> or on .mw-headline (MW 1.43+ wrappers) |
|||
function anchorForHeadingEl(hEl) { |
function anchorForHeadingEl(hEl) { |
||
if (!hEl) return null; |
if (!hEl) return null; |
||
var span = hEl.querySelector && hEl.querySelector('.mw-headline[id]'); |
var span = hEl.querySelector && hEl.querySelector('.mw-headline[id]'); |
||
if (span) return span; |
if (span) return span; |
||
return hEl.id ? hEl : null; |
return hEl.id ? hEl : null; |
||
} |
} |
||
/* ---------------- section open logic ---------------- */ |
|||
// Find the element that actually toggles the H2 section (owns aria-expanded / aria-controls) |
|||
// Try to locate the *actual* toggle that MobileFrontend attached. |
|||
function getH2Toggle(h2El) { |
function getH2Toggle(h2El) { |
||
if (!h2El) return null; |
if (!h2El) return null; |
||
var |
var wrapper = h2El.closest('.mw-heading') || h2El.parentElement || h2El; |
||
// |
// Most robust: a button with aria-controls; otherwise any control with aria-expanded. |
||
var ctrl = |
var ctrl = wrapper.querySelector('button[aria-controls], [data-event-name="section-toggle"], .mf-section-toggle'); |
||
if (ctrl) |
if (!ctrl) ctrl = wrapper.querySelector('[aria-expanded]'); |
||
// Legacy: the H2 or its sibling acts as the toggle. |
|||
// Next-best: any descendant exposing aria-expanded |
|||
if (!ctrl && (h2El.hasAttribute('aria-expanded') || h2El.classList.contains('section-heading') || h2El.classList.contains('collapsible-heading'))) ctrl = h2El; |
|||
ctrl = w.querySelector('[aria-expanded]'); |
|||
if (!ctrl && h2El.previousElementSibling && (h2El.previousElementSibling.matches('[aria-expanded], .section-heading, .collapsible-heading'))) ctrl = h2El.previousElementSibling; |
|||
if (ctrl) return ctrl; |
|||
if (!ctrl && h2El.nextElementSibling && (h2El.nextElementSibling.matches('[aria-expanded], .section-heading, .collapsible-heading'))) ctrl = h2El.nextElementSibling; |
|||
// Legacy: the heading itself behaves as the toggle |
|||
return ctrl; |
|||
if (h2El.hasAttribute('aria-expanded') || h2El.classList.contains('section-heading') || |
|||
h2El.classList.contains('collapsible-heading')) { |
|||
return h2El; |
|||
} |
|||
// As a last resort, some old MF put a separate preceding/next sibling as the toggle |
|||
var prev = h2El.previousElementSibling, next = h2El.nextElementSibling; |
|||
if (prev && (prev.matches('[aria-expanded], .section-heading, .collapsible-heading'))) return prev; |
|||
if (next && (next.matches('[aria-expanded], .section-heading, .collapsible-heading'))) return next; |
|||
return null; |
|||
} |
} |
||
function h2IsCollapsed(h2El) { |
function h2IsCollapsed(h2El) { |
||
if (!h2El) return false; |
if (!h2El) return false; |
||
var toggle = getH2Toggle(h2El); |
|||
// Newer pattern: wrapper section with aria-expanded controls visibility. |
|||
if (toggle) { |
|||
var sec = h2El.closest('section[aria-expanded]'); |
|||
if (sec) return sec.getAttribute('aria-expanded') === 'false'; |
|||
// Toggle state on heading/button itself. |
|||
var t = getH2Toggle(h2El); |
|||
if (t) { |
|||
var ae = t.getAttribute('aria-expanded'); |
|||
if (ae === 'false') return true; |
if (ae === 'false') return true; |
||
if (ae === 'true') return false; |
if (ae === 'true') return false; |
||
var cid = |
var cid = t.getAttribute('aria-controls'); |
||
if (cid) { |
if (cid) { |
||
var block = document.getElementById(cid); |
var block = document.getElementById(cid); |
||
| Line 97: | Line 89: | ||
} |
} |
||
} |
} |
||
// Legacy sibling block |
// Legacy: sibling .collapsible-block right after H2 |
||
var sib = h2El.nextElementSibling; |
var sib = h2El.nextElementSibling; |
||
if (sib && sib.classList.contains('collapsible-block')) return !sib.classList.contains('open-block'); |
if (sib && sib.classList.contains('collapsible-block')) return !sib.classList.contains('open-block'); |
||
// Newer wrapper pattern: <section aria-expanded="false"> around heading+content |
|||
var sec = h2El.closest('section[aria-expanded]'); |
|||
if (sec) return sec.getAttribute('aria-expanded') === 'false'; |
|||
return false; |
return false; |
||
} |
} |
||
// Synthesize a robust "activation" to trigger MF's own handler if present. |
|||
function fireActivation(el) { |
|||
function activate(el) { |
|||
// Fire a sequence of events so whichever MF handler is present reacts |
|||
var |
var ev = { bubbles: true, cancelable: true, view: window }; |
||
try { el.dispatchEvent(new |
try { el.dispatchEvent(new MouseEvent('mousedown', ev)); } catch (_) {} |
||
try { el.dispatchEvent(new MouseEvent(' |
try { el.dispatchEvent(new MouseEvent('mouseup', ev)); } catch (_) {} |
||
try { el.dispatchEvent(new |
try { el.dispatchEvent(new MouseEvent('click', ev)); } catch (_) { el.click(); } |
||
try { el.dispatchEvent(new TouchEvent('touchend', opts)); } catch (_) {} |
|||
try { el.dispatchEvent(new MouseEvent('mouseup', opts)); } catch (_) {} |
|||
try { el.dispatchEvent(new MouseEvent('click', opts)); } catch (_) { el.click(); } |
|||
} |
} |
||
// **Guarantee** the H2 section is open: |
|||
// Open H2 if needed; resolve when open (or after timeout) |
|||
// 1) try MF's toggle; 2) if still closed, **force-open** the DOM (wrapper+block). |
|||
function ensureH2Open(h2El) { |
function ensureH2Open(h2El) { |
||
return new Promise(function (resolve) { |
return new Promise(function (resolve) { |
||
| Line 123: | Line 110: | ||
var toggle = getH2Toggle(h2El); |
var toggle = getH2Toggle(h2El); |
||
var |
var obs = null, done = false; |
||
function finish() { if (!done) { done = true; if (obs) obs.disconnect(); resolve(); } } |
|||
// Observe changes to aria-expanded / classes / hidden |
|||
var obs = null; |
|||
if (window.MutationObserver) { |
if (window.MutationObserver) { |
||
obs = new MutationObserver(function () { |
obs = new MutationObserver(function () { |
||
if (!h2IsCollapsed(h2El)) |
if (!h2IsCollapsed(h2El)) finish(); |
||
if (obs) obs.disconnect(); |
|||
resolve(); |
|||
} |
|||
}); |
}); |
||
var targets = []; |
var targets = []; |
||
if (toggle) targets.push(toggle); |
if (toggle) targets.push(toggle); |
||
var cid = toggle && toggle.getAttribute('aria-controls'); |
|||
var controlled = cid && document.getElementById(cid); |
|||
if (controlled) targets.push(controlled); |
|||
// Also watch the wrapper <section aria-expanded> |
|||
var sec = h2El.closest('section[aria-expanded]'); |
var sec = h2El.closest('section[aria-expanded]'); |
||
if (sec) targets.push(sec); |
if (sec) targets.push(sec); |
||
var cid = toggle && toggle.getAttribute('aria-controls'); |
|||
if (targets.length) { |
|||
var block = cid && document.getElementById(cid); |
|||
targets.forEach(function (t) { |
|||
if (block) targets.push(block); |
|||
obs.observe(t, { attributes: true, attributeFilter: ['aria-expanded', 'class', 'hidden'] }); |
|||
targets.forEach(function (t) { |
|||
obs.observe(t, { attributes: true, attributeFilter: ['aria-expanded', 'class', 'hidden', 'style'] }); |
|||
} |
|||
}); |
|||
} |
} |
||
// |
// Step 1: Attempt the *real* toggle |
||
if (toggle) |
if (toggle) activate(toggle); |
||
// |
// Step 2: After a short tick, **force open** if still collapsed |
||
setTimeout(function |
setTimeout(function () { |
||
if (!h2IsCollapsed(h2El)) return; |
if (!h2IsCollapsed(h2El)) return finish(); |
||
if (!triedManual) { |
|||
// Wrapper <section aria-expanded> |
|||
var sec = h2El.closest('section[aria-expanded]'); |
|||
if (sec) sec.setAttribute('aria-expanded', 'true'); |
|||
// Toggle element state |
|||
if (toggle) { |
|||
// 1) If we have a controls target, unhide it + mark open-block |
|||
toggle.setAttribute('aria-expanded', 'true'); |
|||
var cid = toggle.getAttribute('aria-controls'); |
|||
var block = cid && document.getElementById(cid); |
var block = cid && document.getElementById(cid); |
||
if (block) { |
if (block) { |
||
block.hidden = false; |
block.hidden = false; |
||
block.removeAttribute('hidden'); |
block.removeAttribute('hidden'); |
||
block.classList.add('open-block'); |
block.classList.add('open-block'); // legacy open marker |
||
block.style.display = ''; // clear any inline display:none |
|||
} |
|||
// 2) If a wrapper <section aria-expanded> exists, flip it |
|||
var sec = h2El.closest('section[aria-expanded]'); |
|||
if (sec) sec.setAttribute('aria-expanded', 'true'); |
|||
// 3) If legacy sibling block exists, mark it open |
|||
var sib = h2El.nextElementSibling; |
|||
if (sib && sib.classList.contains('collapsible-block')) { |
|||
sib.classList.add('open-block'); |
|||
sib.hidden = false; |
|||
sib.removeAttribute('hidden'); |
|||
} |
} |
||
} |
} |
||
// |
// Legacy sibling block after H2 |
||
var sib = h2El.nextElementSibling; |
|||
if (sib && sib.classList.contains('collapsible-block')) { |
|||
sib.hidden = false; |
|||
sib.removeAttribute('hidden'); |
|||
sib.classList.add('open-block'); |
|||
sib.style.display = ''; |
|||
} |
|||
// Final safety: even if some CSS remains, proceed; scrolling to H3 will now work. |
|||
finish(); |
|||
}, 120); |
}, 120); |
||
// Hard stop to prevent hangs |
|||
setTimeout(function () { |
|||
setTimeout(finish, 900); |
|||
resolve(); // even if still closed, we won’t hang |
|||
}, 900); |
|||
}); |
}); |
||
} |
} |
||
/* ---------- main initializer ---------- */ |
/* ---------------- main initializer ---------------- */ |
||
function initTOC() { |
function initTOC() { |
||
// phones only |
if (window.matchMedia('(min-width: 768px)').matches) return; // phones only |
||
if (mw.config && !mw.config.get('wgIsArticle')) return; // content pages only |
|||
if (window.matchMedia('(min-width: 768px)').matches) return; |
|||
if (!once('cps-open-toc')) return; // avoid duplicates |
|||
// only in article view |
|||
if (mw.config && !mw.config.get('wgIsArticle')) return; |
|||
// avoid duplicate buttons |
|||
if (!once('cps-open-toc')) return; |
|||
var root = getContentRoot(); |
var root = getContentRoot(); |
||
// Build heading list |
// Build heading list + indices |
||
var items = []; |
var items = []; |
||
var indexById = Object.create(null); |
var indexById = Object.create(null); |
||
| Line 208: | Line 187: | ||
var level = parseInt(h.tagName.slice(1), 10); |
var level = parseInt(h.tagName.slice(1), 10); |
||
if (level < 2 || level > 6) return; |
if (level < 2 || level > 6) return; |
||
var anchor = h.querySelector('.mw-headline[id]') || h; |
var anchor = h.querySelector('.mw-headline[id]') || h; // works pre/post Heading-HTML changes :contentReference[oaicite:3]{index=3} |
||
var id = anchor.id || h.id; |
var id = anchor.id || h.id; |
||
var text = (anchor.textContent || h.textContent || '').trim(); |
var text = (anchor.textContent || h.textContent || '').trim(); |
||
| Line 217: | Line 196: | ||
}); |
}); |
||
if (items.length < 3) return; // |
if (items.length < 3) return; // mirror core TOC threshold |
||
// UI: trigger button |
// UI: trigger button |
||
| Line 240: | Line 219: | ||
var header = document.createElement('div'); |
var header = document.createElement('div'); |
||
header.id = 'cps-toc-header'; |
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>'; |
|||
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'); |
var list = document.createElement('ul'); |
||
| Line 262: | Line 239: | ||
document.body.appendChild(overlay); |
document.body.appendChild(overlay); |
||
// |
// Open/close overlay |
||
var lastFocus = null; |
var lastFocus = null; |
||
function openOverlay() { |
function openOverlay() { |
||
| Line 269: | Line 246: | ||
overlay.setAttribute('aria-hidden', 'false'); |
overlay.setAttribute('aria-hidden', 'false'); |
||
document.body.style.overflow = 'hidden'; |
document.body.style.overflow = 'hidden'; |
||
var |
var first = list.querySelector('a'); |
||
if ( |
if (first) first.focus({ preventScroll: true }); |
||
} |
} |
||
function closeOverlay() { |
function closeOverlay() { |
||
| Line 278: | Line 255: | ||
if (lastFocus && lastFocus.focus) lastFocus.focus({ preventScroll: true }); |
if (lastFocus && lastFocus.focus) lastFocus.focus({ preventScroll: true }); |
||
} |
} |
||
btn.style.display = 'flex'; |
btn.style.display = 'flex'; |
||
btn.addEventListener('click', openOverlay); |
btn.addEventListener('click', openOverlay); |
||
| Line 284: | Line 262: | ||
overlay.addEventListener('keydown', function (e) { if (e.key === 'Escape') closeOverlay(); }); |
overlay.addEventListener('keydown', function (e) { if (e.key === 'Escape') closeOverlay(); }); |
||
// parent H2 lookup |
|||
function parentH2For(id) { |
function parentH2For(id) { |
||
var idx = indexById[id]; |
var idx = indexById[id]; |
||
| Line 292: | Line 269: | ||
} |
} |
||
// |
// NAV: open parent H2 (forced if needed) THEN scroll to the H3+ target |
||
list.addEventListener('click', function (e) { |
list.addEventListener('click', function (e) { |
||
var a = e.target && e.target.closest('a'); |
var a = e.target && e.target.closest('a'); |
||
| Line 302: | Line 279: | ||
var level = li ? parseInt(li.getAttribute('data-level') || '0', 10) : 0; |
var level = li ? parseInt(li.getAttribute('data-level') || '0', 10) : 0; |
||
closeOverlay(); |
closeOverlay(); // let layout settle first (iOS) |
||
// H3+ — ensure its parent H2 is open first |
|||
if (level >= 3) { |
if (level >= 3) { |
||
var p = parentH2For(targetId); |
var p = parentH2For(targetId); |
||
| Line 310: | Line 286: | ||
var h2El = headingElById[p.id]; |
var h2El = headingElById[p.id]; |
||
ensureH2Open(h2El).then(function () { |
ensureH2Open(h2El).then(function () { |
||
// Prefer the intended H3 |
// Prefer the intended H3; fall back to H2 anchor if needed |
||
var dest = document.getElementById(targetId) || anchorForHeadingEl(h2El) || h2El; |
var dest = document.getElementById(targetId) || anchorForHeadingEl(h2El) || h2El; |
||
if (!dest) return; |
if (!dest) return; |
||
| Line 326: | Line 302: | ||
} |
} |
||
// H2 or no parent |
// H2 (or no parent): direct scroll |
||
var |
var dest = document.getElementById(targetId) || |
||
(level === 2 ? anchorForHeadingEl(headingElById[targetId]) : null); |
(level === 2 ? anchorForHeadingEl(headingElById[targetId]) : null); |
||
if (! |
if (!dest) return; |
||
requestAnimationFrame(function () { |
requestAnimationFrame(function () { |
||
smoothScrollTo( |
smoothScrollTo(dest); |
||
setTimeout(function () { |
setTimeout(function () { |
||
if (history && history.replaceState) history.replaceState(null, '', '#' + ( |
if (history && history.replaceState) history.replaceState(null, '', '#' + (dest.id || targetId)); |
||
else location.hash = |
else location.hash = dest.id || targetId; |
||
}, 120); |
}, 120); |
||
}); |
}); |
||
}); |
}); |
||
// Hide/show |
// Hide/show the floating button on rotation |
||
window.addEventListener('resize', function () { |
window.addEventListener('resize', function () { |
||
if (window.matchMedia('(min-width: 768px)').matches) { btn.style.display = 'none'; closeOverlay(); } |
if (window.matchMedia('(min-width: 768px)').matches) { btn.style.display = 'none'; closeOverlay(); } |
||
| Line 346: | Line 322: | ||
} |
} |
||
/* ---------- bootstrap ---------- */ |
/* ---------------- bootstrap ---------------- */ |
||
if (window.mw && mw.loader) { |
if (window.mw && mw.loader) { |
||
// |
// Wait for MobileFrontend client (sections/toggles are provided by it). :contentReference[oaicite:4]{index=4} |
||
mw.loader.using('mobile.startup').then(function () { |
mw.loader.using('mobile.startup').then(function () { |
||
onReady(function () { if (isMobileSite()) initTOC(); }); |
onReady(function () { if (isMobileSite()) initTOC(); }); |
||
if (mw.hook) mw.hook('wikipage.content').add(function () { |
if (mw.hook) mw.hook('wikipage.content').add(function () { if (isMobileSite()) initTOC(); }); |
||
if (isMobileSite()) initTOC(); |
|||
}); |
|||
}); |
}); |
||
} else { |
} else { |
||
Revision as of 22:35, 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 (phones); ALWAYS open parent H2 before scrolling to H3+ */
(function () {
/* ---------------- utilities ---------------- */
function isMobileSite() {
// Stable MF signal on <body> for gadgets/scripts.
return document.body && document.body.classList.contains('mw-mf'); // MobileFrontend active. :contentReference[oaicite:1]{index=1}
}
function once(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
);
}
// Scroll while compensating for any sticky headers in mobile skins.
function smoothScrollTo(el) {
var offset = 0;
try {
document.querySelectorAll('header, .minerva-header, .mw-header, .site-header, #header, .header').forEach(function (node) {
var cs = 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); }
}
// In MW 1.43+ IDs may be on .mw-headline (inside the heading wrapper). :contentReference[oaicite:2]{index=2}
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;
}
/* ---------------- section open logic ---------------- */
// Try to locate the *actual* toggle that MobileFrontend attached.
function getH2Toggle(h2El) {
if (!h2El) return null;
var wrapper = h2El.closest('.mw-heading') || h2El.parentElement || h2El;
// Most robust: a button with aria-controls; otherwise any control with aria-expanded.
var ctrl = wrapper.querySelector('button[aria-controls], [data-event-name="section-toggle"], .mf-section-toggle');
if (!ctrl) ctrl = wrapper.querySelector('[aria-expanded]');
// Legacy: the H2 or its sibling acts as the toggle.
if (!ctrl && (h2El.hasAttribute('aria-expanded') || h2El.classList.contains('section-heading') || h2El.classList.contains('collapsible-heading'))) ctrl = h2El;
if (!ctrl && h2El.previousElementSibling && (h2El.previousElementSibling.matches('[aria-expanded], .section-heading, .collapsible-heading'))) ctrl = h2El.previousElementSibling;
if (!ctrl && h2El.nextElementSibling && (h2El.nextElementSibling.matches('[aria-expanded], .section-heading, .collapsible-heading'))) ctrl = h2El.nextElementSibling;
return ctrl;
}
function h2IsCollapsed(h2El) {
if (!h2El) return false;
// Newer pattern: wrapper section with aria-expanded controls visibility.
var sec = h2El.closest('section[aria-expanded]');
if (sec) return sec.getAttribute('aria-expanded') === 'false';
// Toggle state on heading/button itself.
var t = getH2Toggle(h2El);
if (t) {
var ae = t.getAttribute('aria-expanded');
if (ae === 'false') return true;
if (ae === 'true') return false;
var cid = t.getAttribute('aria-controls');
if (cid) {
var block = document.getElementById(cid);
if (block) {
if (block.hidden || block.getAttribute('hidden') !== null) return true;
if (block.classList.contains('collapsible-block') && !block.classList.contains('open-block')) return true;
}
}
}
// Legacy: sibling .collapsible-block right after H2
var sib = h2El.nextElementSibling;
if (sib && sib.classList.contains('collapsible-block')) return !sib.classList.contains('open-block');
return false;
}
// Synthesize a robust "activation" to trigger MF's own handler if present.
function activate(el) {
var ev = { bubbles: true, cancelable: true, view: window };
try { el.dispatchEvent(new MouseEvent('mousedown', ev)); } catch (_) {}
try { el.dispatchEvent(new MouseEvent('mouseup', ev)); } catch (_) {}
try { el.dispatchEvent(new MouseEvent('click', ev)); } catch (_) { el.click(); }
}
// **Guarantee** the H2 section is open:
// 1) try MF's toggle; 2) if still closed, **force-open** the DOM (wrapper+block).
function ensureH2Open(h2El) {
return new Promise(function (resolve) {
if (!h2El || !h2IsCollapsed(h2El)) return resolve();
var toggle = getH2Toggle(h2El);
var obs = null, done = false;
function finish() { if (!done) { done = true; if (obs) obs.disconnect(); resolve(); } }
if (window.MutationObserver) {
obs = new MutationObserver(function () {
if (!h2IsCollapsed(h2El)) finish();
});
var targets = [];
if (toggle) targets.push(toggle);
var sec = h2El.closest('section[aria-expanded]');
if (sec) targets.push(sec);
var cid = toggle && toggle.getAttribute('aria-controls');
var block = cid && document.getElementById(cid);
if (block) targets.push(block);
targets.forEach(function (t) {
obs.observe(t, { attributes: true, attributeFilter: ['aria-expanded', 'class', 'hidden', 'style'] });
});
}
// Step 1: Attempt the *real* toggle
if (toggle) activate(toggle);
// Step 2: After a short tick, **force open** if still collapsed
setTimeout(function () {
if (!h2IsCollapsed(h2El)) return finish();
// Wrapper <section aria-expanded>
var sec = h2El.closest('section[aria-expanded]');
if (sec) sec.setAttribute('aria-expanded', 'true');
// Toggle element state
if (toggle) {
toggle.setAttribute('aria-expanded', 'true');
var cid = toggle.getAttribute('aria-controls');
var block = cid && document.getElementById(cid);
if (block) {
block.hidden = false;
block.removeAttribute('hidden');
block.classList.add('open-block'); // legacy open marker
block.style.display = ''; // clear any inline display:none
}
}
// Legacy sibling block after H2
var sib = h2El.nextElementSibling;
if (sib && sib.classList.contains('collapsible-block')) {
sib.hidden = false;
sib.removeAttribute('hidden');
sib.classList.add('open-block');
sib.style.display = '';
}
// Final safety: even if some CSS remains, proceed; scrolling to H3 will now work.
finish();
}, 120);
// Hard stop to prevent hangs
setTimeout(finish, 900);
});
}
/* ---------------- main initializer ---------------- */
function initTOC() {
if (window.matchMedia('(min-width: 768px)').matches) return; // phones only
if (mw.config && !mw.config.get('wgIsArticle')) return; // content pages only
if (!once('cps-open-toc')) return; // avoid duplicates
var root = getContentRoot();
// Build heading list + indices
var items = [];
var indexById = Object.create(null);
var headingElById = Object.create(null);
root.querySelectorAll('h2, h3, h4, h5, h6').forEach(function (h) {
var level = parseInt(h.tagName.slice(1), 10);
if (level < 2 || level > 6) return;
var anchor = h.querySelector('.mw-headline[id]') || h; // works pre/post Heading-HTML changes :contentReference[oaicite:3]{index=3}
var id = anchor.id || h.id;
var text = (anchor.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);
// Open/close overlay
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(); });
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;
}
// NAV: open parent H2 (forced if needed) THEN scroll to the H3+ 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;
closeOverlay(); // let layout settle first (iOS)
if (level >= 3) {
var p = parentH2For(targetId);
if (p) {
var h2El = headingElById[p.id];
ensureH2Open(h2El).then(function () {
// Prefer the intended H3; fall back to H2 anchor if needed
var dest = document.getElementById(targetId) || anchorForHeadingEl(h2El) || h2El;
if (!dest) return;
requestAnimationFrame(function () {
smoothScrollTo(dest);
var finalId = dest.id || targetId;
setTimeout(function () {
if (history && history.replaceState) history.replaceState(null, '', '#' + finalId);
else location.hash = finalId;
}, 120);
});
});
return;
}
}
// H2 (or no parent): direct scroll
var dest = document.getElementById(targetId) ||
(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;
}, 120);
});
});
// Hide/show the floating button 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 ---------------- */
if (window.mw && mw.loader) {
// Wait for MobileFrontend client (sections/toggles are provided by it). :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 {
onReady(function () { if (isMobileSite()) initTOC(); });
}
})();