Jump to content

MediaWiki:Common.js: Difference between revisions

From Insurer Brain
Content deleted Content added
No edit summary
No edit summary
Line 141: Line 141:
document.body;
document.body;


// Collect headings (H2–H6). Prefer spans with .mw-headline (stable anchor ids)
// Collect headings (H2–H5; h6 is bold body text, excluded from the TOC).
// Prefer spans with .mw-headline (stable anchor ids)
var items = [];
var items = [];
var headings = root.querySelectorAll('h2, h3, h4, h5, h6');
var headings = root.querySelectorAll('h2, h3, h4, h5');
headings.forEach(function (h) {
headings.forEach(function (h) {
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 > 5) return;
var headline = h.querySelector('.mw-headline') || h;
var headline = h.querySelector('.mw-headline') || h;
var id = headline.id || h.id;
var id = headline.id || h.id;
Line 688: Line 689:
}, function (e) { mw.log('TermMap review: mediawiki.api failed to load', e); });
}, function (e) { mw.log('TermMap review: mediawiki.api failed to load', e); });
});
});


/* ── Hide level-6 headings from the sidebar (Vector) TOC ─────────────────────
MediaWiki's TOC classes (vector-toc-level-N) encode only a COMPACTED nesting
depth, NOT the original heading tag — when levels jump (h3->h6) it still only
increments one level — so CSS cannot reliably target h6. Resolve each TOC
entry to its body heading and hide the ones that are actually <h6>. Safe: it
only ever hides h6 (never h2–h5). The mobile overlay excludes h6 separately
(above). */
(function () {
function headingFor(anchor) {
if (!anchor) { return null; }
var el = document.getElementById(anchor);
if (!el) {
try { el = document.getElementById(decodeURIComponent(anchor)); } catch (e) {}
}
if (!el) { return null; }
if (el.matches && el.matches('h1,h2,h3,h4,h5,h6')) { return el; }
return el.closest ? el.closest('h1,h2,h3,h4,h5,h6') : null;
}
function pruneTocH6() {
var items = document.querySelectorAll('.vector-toc .vector-toc-list-item');
Array.prototype.forEach.call(items, function (li) {
var a = li.querySelector('a.vector-toc-link');
if (!a) { return; }
var href = a.getAttribute('href') || '';
if (href.charAt(0) !== '#' || href.length < 2) { return; }
var h = headingFor(href.slice(1));
if (h && h.tagName === 'H6') { li.style.display = 'none'; }
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', pruneTocH6);
} else {
pruneTocH6();
}
// Vector can lazily (re)build the pinned TOC; re-run on its content hook.
if (window.mw && mw.hook) { mw.hook('wikipage.content').add(pruneTocH6); }
})();

Revision as of 23:39, 3 July 2026

/* Any JavaScript here will be loaded for all users on every page load. */
/**
 * Keep code in MediaWiki:Common.js to a minimum as it is unconditionally
 * loaded for all users on every wiki page. If possible create a gadget that is
 * enabled by default instead of adding it here (since gadgets are fully
 * optimized ResourceLoader modules with possibility to add dependencies etc.)
 *
 * Since Common.js isn't a gadget, there is no place to declare its
 * dependencies, so we have to lazy load them with mw.loader.using on demand and
 * then execute the rest in the callback. In most cases these dependencies will
 * be loaded (or loading) already and the callback will not be delayed. In case a
 * dependency hasn't arrived yet it'll make sure those are loaded before this.
 */

/* global mw, $ */
/* jshint strict:false, browser:true */

mw.loader.using( [ 'mediawiki.util' ] ).done( function () {
	/* Begin of mw.loader.using callback */

	/**
	 * Map addPortletLink to mw.util
	 * @deprecated: Use mw.util.addPortletLink instead.
	 */
	mw.log.deprecate( window, 'addPortletLink', mw.util.addPortletLink, 'Use mw.util.addPortletLink instead' );

	/**
	 * @source https://www.mediawiki.org/wiki/Snippets/Load_JS_and_CSS_by_URL
	 * @rev 6
	 */
	var extraCSS = mw.util.getParamValue( 'withCSS' ),
		extraJS = mw.util.getParamValue( 'withJS' );

	if ( extraCSS ) {
		if ( extraCSS.match( /^MediaWiki:[^&<>=%#]*\.css$/ ) ) {
			mw.loader.load( '/w/index.php?title=' + extraCSS + '&action=raw&ctype=text/css', 'text/css' );
		} else {
			mw.notify( 'Only pages from the MediaWiki namespace are allowed.', { title: 'Invalid withCSS value' } );
		}
	}

	if ( extraJS ) {
		if ( extraJS.match( /^MediaWiki:[^&<>=%#]*\.js$/ ) ) {
			mw.loader.load( '/w/index.php?title=' + extraJS + '&action=raw&ctype=text/javascript' );
		} else {
			mw.notify( 'Only pages from the MediaWiki namespace are allowed.', { title: 'Invalid withJS value' } );
		}
	}

	/**
	 * Collapsible tables; reimplemented with mw-collapsible
	 * Styling is also in place to avoid FOUC
	 *
	 * Allows tables to be collapsed, showing only the header. See [[Help:Collapsing]].
	 * @version 3.0.0 (2018-05-20)
	 * @source https://www.mediawiki.org/wiki/MediaWiki:Gadget-collapsibleTables.js
	 * @author [[User:R. Koot]]
	 * @author [[User:Krinkle]]
	 * @author [[User:TheDJ]]
	 * @deprecated Since MediaWiki 1.20: Use class="mw-collapsible" instead which
	 * is supported in MediaWiki core. Shimmable since MediaWiki 1.32
	 *
	 * @param {jQuery} $content
	 */
	function makeCollapsibleMwCollapsible( $content ) {
		var $tables = $content
			.find( 'table.collapsible:not(.mw-collapsible)' )
			.addClass( 'mw-collapsible' );

		$.each( $tables, function ( index, table ) {
			// mw.log.warn( 'This page is using the deprecated class collapsible. Please replace it with mw-collapsible.');
			if ( $( table ).hasClass( 'collapsed' ) ) {
				$( table ).addClass( 'mw-collapsed' );
				// mw.log.warn( 'This page is using the deprecated class collapsed. Please replace it with mw-collapsed.');
			}
		} );
		if ( $tables.length > 0 ) {
			mw.loader.using( 'jquery.makeCollapsible' ).then( function () {
				$tables.makeCollapsible();
			} );
		}
	}
	mw.hook( 'wikipage.content' ).add( makeCollapsibleMwCollapsible );

	/**
	 * Add support to mw-collapsible for autocollapse, innercollapse and outercollapse
	 *
	 * Maintainers: TheDJ
	 */
	function mwCollapsibleSetup( $collapsibleContent ) {
		var $element,
			$toggle,
			autoCollapseThreshold = 2;
		$.each( $collapsibleContent, function ( index, element ) {
			$element = $( element );
			if ( $element.hasClass( 'collapsible' ) ) {
				$element.find( 'tr:first > th:first' ).prepend( $element.find( 'tr:first > * > .mw-collapsible-toggle' ) );
			}
			if ( $collapsibleContent.length >= autoCollapseThreshold && $element.hasClass( 'autocollapse' ) ) {
				$element.data( 'mw-collapsible' ).collapse();
			} else if ( $element.hasClass( 'innercollapse' ) ) {
				if ( $element.parents( '.outercollapse' ).length > 0 ) {
					$element.data( 'mw-collapsible' ).collapse();
				}
			}
			// because of colored backgrounds, style the link in the text color
			// to ensure accessible contrast
			$toggle = $element.find( '.mw-collapsible-toggle' );
			if ( $toggle.length ) {
				// Make the toggle inherit text color (Updated for T333357 2023-04-29)
				if ( $toggle.parent()[ 0 ].style.color ) {
					$toggle.css( 'color', 'inherit' );
					$toggle.find( '.mw-collapsible-text' ).css( 'color', 'inherit' );
				}
			}
		} );
	}

	mw.hook( 'wikipage.collapsibleContent' ).add( mwCollapsibleSetup );

	/* End of mw.loader.using callback */
} );

// CapSach — Sticky TOC overlay (UNRESTRICTED: Works on iPad/Desktop/Mobile)
(function () {

  // 1. REMOVED the "min-width: 768px" check. Now runs everywhere.

  // Only run on pages where it makes sense (Articles/MainPage)
  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–H5; h6 is bold body text, excluded from the TOC).
  // Prefer spans with .mw-headline (stable anchor ids)
  var items = [];
  var headings = root.querySelectorAll('h2, h3, h4, h5');
  headings.forEach(function (h) {
    var level = parseInt(h.tagName.slice(1), 10);
    if (level < 2 || level > 5) 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
  // CHANGED: Lowered requirement to 1 heading so it always shows if there is any structure
  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 });
  }

  // Force button display immediately
  btn.style.display = 'flex';
  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
// 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);

    // === NEW LOGIC START: Scroll to Top for "Contents" ===
    // If the user clicks the "Contents" header (id="mw-toc-heading"), scroll to top (0,0)
// === FIXED CODE ===
if (targetId === 'mw-toc-heading') {
   closeOverlay();
   // Delay scroll to let iOS Safari process the overflow change
   setTimeout(function() {
       try {
           window.scrollTo({ top: 0, behavior: 'smooth' });
       } catch (e) {
           window.scrollTo(0, 0);
       }
       // Fallback for older iOS Safari
       document.documentElement.scrollTop = 0;
       document.body.scrollTop = 0;
   }, 100);
   if (history.replaceState) {
       history.replaceState(null, '', window.location.pathname + window.location.search);
   }
   return;
}
    // === NEW LOGIC END ===

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

  // 2. REMOVED the "resize" event listener that was hiding the button.
  // The button now persists on all screen sizes.
})();

/* Script for Inline Expandable Template */
$(function() {
    $('.inline-expand-trigger').on('click', function() {
        // 1. Toggle the content visibility
        $(this).next('.inline-expand-content').toggle();

        // 2. Toggle the arrow icon
        const currentText = $(this).text();
        $(this).text(
            currentText.includes('▸') ? currentText.replace('▸', '◂') : currentText.replace('◂', '▸')
        );
    });
});

$(document).ready(function() {
    // Check if the button already exists to prevent duplicates
    if ($('#custom-email-btn').length === 0) {

        // Create the email button element
        var emailBtn = $('<a>', {
            id: 'custom-email-btn',
            href: 'mailto:bananabot@axabrain.com',
            // Simple accessible title
            title: 'Contact AXA BRAIN Services'
        });

        // Add it to the body of the page
        $('body').append(emailBtn);
    }
});

/* Open AXA BRAIN AI Assistant when clicking the logo */
$(document).ready(function() {
    $('.fullscreen-logo').css('cursor', 'pointer').click(function(e) {
        e.preventDefault();

        // Method 1: Click the AI Assistant floating icon
        var $aiButton = $('img[src*="ai-icon.png"]').closest('div, button, a');
        if ($aiButton.length > 0) {
            $aiButton.trigger('click');
            return;
        }

        // Method 2: Try the extension's trigger class
        var $trigger = $('.ext-aiassistant-trigger, .ext-aiassistant');
        if ($trigger.length > 0) {
            $trigger.first().trigger('click');
            return;
        }

        console.log("AXA BRAIN Assistant button not found on this page.");
    });
});

/* Inline footnotes ({{footnote}}). We render the note OURSELVES, appended to
   <body> (the ROOT stacking context), so a table's sticky column can never
   cover it and it behaves identically across browsers. The native title=""
   tooltip is unreliable + unstyled, so we move it to data-fn (the bot still
   reads the hidden .ed-fn-body span) and show:
     - PHONE  (no hover): tap a cue  -> full-width banner at the top; tap to dismiss.
     - DESKTOP (hover):   hover a cue -> a small popover beside the cue.
   If this script never runs, the title="" stays and the native tooltip is the
   graceful fallback. */
(function () {
  var cues = document.querySelectorAll('.ed-fn');
  if (!cues.length) { return; }

  // Suppress the native tooltip; keep the note text in data-fn.
  Array.prototype.forEach.call(cues, function (el) {
    if (el.hasAttribute('title')) {
      el.setAttribute('data-fn', el.getAttribute('title'));
      el.removeAttribute('title');
    }
  });

  var box = null, activeCue = null;
  function noteOf(el) { return el.getAttribute('data-fn') || ''; }
  function cueOf(e) {
    var t = e.target;
    return (t && t.closest) ? t.closest('.ed-fn') : null;
  }
  function close() {
    if (box) { box.remove(); box = null; }
    activeCue = null;
    document.removeEventListener('click', onAway, true);
  }
  function onAway(e) {
    if (!cueOf(e)) { close(); }
  }

  var touch = window.matchMedia && window.matchMedia('(hover: none)').matches;

  if (touch) {
    // Phone: full-width banner pinned to the top; the next tap anywhere dismisses.
    document.addEventListener('click', function (e) {
      var cue = cueOf(e);
      if (!cue) { return; }
      e.preventDefault();
      var txt = noteOf(cue);
      if (!txt) { return; }
      e.stopPropagation();
      close();
      box = document.createElement('div');
      box.className = 'ed-fn-banner';
      box.textContent = txt;
      document.body.appendChild(box);
      setTimeout(function () {
        document.addEventListener('click', onAway, true);
      }, 0);
    }, false);
  } else {
    // Desktop: a styled popover beside the cue while hovering it.
    document.addEventListener('mouseover', function (e) {
      var cue = cueOf(e);
      if (!cue || cue === activeCue) { return; }
      var txt = noteOf(cue);
      if (!txt) { return; }
      close();
      activeCue = cue;
      box = document.createElement('div');
      box.className = 'ed-fn-popover';
      box.textContent = txt;
      document.body.appendChild(box);
      var r = cue.getBoundingClientRect();
      var left = Math.max(8, Math.min(r.left, window.innerWidth - box.offsetWidth - 8));
      var top = r.top - box.offsetHeight - 8;          // above the cue...
      if (top < 8) { top = r.bottom + 8; }             // ...or below if no room
      box.style.left = left + 'px';
      box.style.top = top + 'px';
    });
    document.addEventListener('mouseout', function (e) {
      if (!activeCue) { return; }
      var to = e.relatedTarget;
      if (to && to.closest && to.closest('.ed-fn') === activeCue) { return; }
      close();
    });
    window.addEventListener('scroll', function () { if (box) { close(); } }, true);
  }
})();

/* ── Datacheck confirm/correct gadget ───────────────────────────────────────
   On a Datacheck: page (namespace 3006), fill each Module:ReportedTable row's
   action cells — .rt-confirm / .rt-reject / .rt-override — with one button each
   (Confirm toggle · Reject · Correct→enter a number), and mirror the verdict in the
   .rt-status badge. Writes the verdict straight into the underlying Data:<...>.json
   page under the REVIEWER'S OWN session (no bot creds). DOM order within each class
   == records[] order (one per record); the exact Data title comes from the hidden
   .rt-data-title marker. Verdicts survive a re-publish via wiki_extract.merge_verdicts
   (value-gated). Anonymous users see the Status badge only (no buttons). */
$(function () {
  if (!(window.mw && mw.config) || mw.config.get('wgNamespaceNumber') !== 3006) { return; }
  var confirmCells = document.querySelectorAll('.rt-confirm');
  var rejectCells = document.querySelectorAll('.rt-reject');
  var overrideCells = document.querySelectorAll('.rt-override');
  var statusCells = document.querySelectorAll('.rt-status');
  if (!confirmCells.length) { return; }
  if (!mw.config.get('wgUserName')) { mw.log('Datacheck: log in to enable confirm controls.'); return; }

  // Data page title from the hidden marker, else derived from the page name (Datacheck:X -> Data:X.json).
  var marker = document.querySelector('.rt-data-title');
  var dataTitle = marker ? (marker.textContent || '').trim() : '';
  if (!dataTitle) {
    var pn = mw.config.get('wgPageName') || '', rest = pn.replace(/^Datacheck:/, '');
    if (rest && rest !== pn) { dataTitle = 'Data:' + rest + '.json'; }
  }
  if (!dataTitle) { mw.log('Datacheck: could not resolve the Data page title.'); return; }

  function notify(msg) { if (mw.notify) { mw.notify(msg); } else { mw.log(msg); } }

  mw.loader.using(['mediawiki.api']).then(function () {   // mw.notify is global; only the API needs loading
    var api = new mw.Api(), data = null, baseRevId = null;

    function fetchAndRender() {
      api.get({ action: 'query', prop: 'revisions', rvprop: 'content|ids',
                rvslots: 'main', titles: dataTitle, formatversion: 2 }).done(function (res) {
        var page = res.query && res.query.pages && res.query.pages[0];
        var rev = page && page.revisions && page.revisions[0];
        if (!rev) { notify('Datacheck: data page not found — ' + dataTitle); return; }
        baseRevId = rev.revid;
        var content = rev.slots ? rev.slots.main.content : rev.content;
        try { data = JSON.parse(content); }
        catch (e) { notify('Datacheck: bad JSON in ' + dataTitle); return; }
        render();
      }).fail(function (code) { notify('Datacheck: load failed — ' + code); });
    }

    function save(okMsg) {
      api.postWithEditToken({
        action: 'edit', title: dataTitle, contentmodel: 'json',
        text: JSON.stringify(data, null, 2),
        summary: 'Datacheck: human verdict via confirm gadget', baserevid: baseRevId
      }).done(function (res) {
        if (res.edit && res.edit.newrevid) { baseRevId = res.edit.newrevid; }
        render();
        notify(okMsg || 'Datacheck: saved.');
      }).fail(function (code) {
        if (code === 'editconflict') { notify('Datacheck: edit conflict — reloading.'); fetchAndRender(); }
        else { notify('Datacheck: save failed — ' + code); }
      });
    }

    // Set the always-present verdict enum (unreviewed | confirmed | rejected | overridden); un-confirm /
    // un-reject -> 'unreviewed'. Drops the pin + override fields so only the active verdict's fields remain.
    function setStatus(rec, status, extra) {
      delete rec.confirmed_rev; delete rec.override_reason; delete rec.alt_source;
      rec.human_status = status || 'unreviewed';
      for (var k in (extra || {})) { rec[k] = extra[k]; }
    }

    function toggleConfirm(rec) {
      if (rec.human_status === 'confirmed') { setStatus(rec, 'unreviewed'); }
      else { setStatus(rec, 'confirmed', { confirmed_rev: data.source_revision || null }); }
      save();
    }

    function toggleReject(rec) {
      if (rec.human_status === 'rejected') { setStatus(rec, 'unreviewed'); }
      else { setStatus(rec, 'rejected', { confirmed_rev: data.source_revision || null }); }
      save();
    }

    function correctRow(rec) {
      var hint = 'measure=' + rec.measure + ', scale=' + (rec.scale || 1) +
                 (rec.currency ? ', ' + rec.currency : '');
      var entered = window.prompt(
        'Correct value for "' + rec.label + '" [' + (rec.business_line || 'Total') + '/' +
        (rec.business_unit || 'Group') + ']\n(' + hint + ' — enter the stored value):', String(rec.value));
      if (entered === null) { return; }
      var num = parseFloat(String(entered).replace(/[,\s]/g, ''));
      if (isNaN(num)) { notify('Datacheck: not a number — ' + entered); return; }
      var reason = window.prompt('Reason (optional):', rec.override_reason || 'manual correction') || 'manual correction';
      setStatus(rec, 'overridden', { value: num, confirmed_rev: data.source_revision || null, override_reason: reason });
      save('Datacheck: override saved (' + num + ').');
    }

    // One <button> per action cell (styled as .rt-btn in Common.css); the active verdict's button is filled.
    function btn(glyph, title, active, variant, handler) {
      var b = document.createElement('button');
      b.type = 'button'; b.textContent = glyph; b.title = title;
      b.className = 'rt-btn rt-btn--' + variant + (active ? ' is-active' : '');
      b.onclick = function (e) { e.preventDefault(); handler(); };
      return b;
    }
    function fill(cell, node) { cell.innerHTML = ''; cell.appendChild(node); }

    function render() {
      if (!data || !data.records) { return; }
      var n = data.records.length;
      if (confirmCells.length !== n || rejectCells.length !== n ||
          overrideCells.length !== n || statusCells.length !== n) {
        notify('Datacheck: table out of sync with the data page — reload the page.'); return;
      }
      Array.prototype.forEach.call(confirmCells, function (cCell, i) {
        var rec = data.records[i], status = rec.human_status || 'unreviewed';
        fill(cCell, btn('✓', status === 'confirmed' ? 'Confirmed — click to un-confirm' : 'Confirm',
          status === 'confirmed', 'confirm', function () { toggleConfirm(rec); }));
        fill(rejectCells[i], btn('✗',
          status === 'rejected' ? 'Rejected — click to clear' : 'Reject (wrong, no value yet)',
          status === 'rejected', 'reject', function () { toggleReject(rec); }));
        fill(overrideCells[i], btn('✎', 'Correct — enter the right number (override)',
          status === 'overridden', 'override', function () { correctRow(rec); }));
        var s = statusCells[i];
        s.className = 'rt-status rt-status-' + status;
        s.textContent = (status === 'confirmed') ? '✓ confirmed'
          : (status === 'rejected') ? '✗ rejected'
          : (status === 'overridden') ? ('✎ overridden → ' + rec.value)
          : 'unreviewed';
      });
    }

    fetchAndRender();
  }, function (e) { mw.log('Datacheck: mediawiki.api failed to load', e); });
});


/* ── Datacheck term_map review gadget ────────────────────────────────────────
   On a Datacheck: page that renders Module:TermMap in review mode, turn each row's
   .tm-validate / .tm-redo controls into Validate / Redo buttons. Each click prompts
   for a comment (REQUIRED) and writes review_status + comment + reviewed_by/at into the
   matching Data:term_map.json entry — keyed by the row's hidden .tm-key (the JSON key),
   under the REVIEWER'S OWN session (no bot creds). Reviews survive a redeploy via
   deploy.py term_map_data merge-forward. Anonymous users see the badge + comment only. */
$(function () {
  if (!(window.mw && mw.config) || mw.config.get('wgNamespaceNumber') !== 3006) { return; }
  var vCells = document.querySelectorAll('.tm-validate');
  if (!vCells.length) { return; }                       // not a term_map review page
  if (!mw.config.get('wgUserName')) { mw.log('TermMap review: log in to enable controls.'); return; }

  var marker = document.querySelector('.tm-data-title');
  var dataTitle = marker ? (marker.textContent || '').trim() : 'Data:term_map.json';

  function notify(msg) { if (mw.notify) { mw.notify(msg); } else { mw.log(msg); } }
  function nowIso() { return new Date().toISOString().slice(0, 19) + 'Z'; }

  mw.loader.using(['mediawiki.api']).then(function () {
    var api = new mw.Api(), data = null, baseRevId = null, rows = [];

    function collect() {                                 // one entry per review row, mapped by .tm-key
      rows = [];
      Array.prototype.forEach.call(vCells, function (vCell) {
        var tr = vCell.closest ? vCell.closest('tr') : null;
        if (!tr) { return; }
        var keyEl = tr.querySelector('.tm-key');
        rows.push({
          key: keyEl ? (keyEl.textContent || '').trim() : '',
          vCell: vCell, rCell: tr.querySelector('.tm-redo'),
          badge: tr.querySelector('.rt-status'), comment: tr.querySelector('.tm-comment')
        });
      });
    }

    function fetchAndRender() {
      api.get({ action: 'query', prop: 'revisions', rvprop: 'content|ids',
                rvslots: 'main', titles: dataTitle, formatversion: 2 }).done(function (res) {
        var page = res.query && res.query.pages && res.query.pages[0];
        var rev = page && page.revisions && page.revisions[0];
        if (!rev) { notify('TermMap: data page not found — ' + dataTitle); return; }
        baseRevId = rev.revid;
        var content = rev.slots ? rev.slots.main.content : rev.content;
        try { data = JSON.parse(content); }
        catch (e) { notify('TermMap: bad JSON in ' + dataTitle); return; }
        render();
      }).fail(function (code) { notify('TermMap: load failed — ' + code); });
    }

    function save(okMsg) {
      api.postWithEditToken({
        action: 'edit', title: dataTitle, contentmodel: 'json',
        text: JSON.stringify(data, null, 4),
        summary: 'TermMap review: human verdict via review gadget', baserevid: baseRevId
      }).done(function (res) {
        if (res.edit && res.edit.newrevid) { baseRevId = res.edit.newrevid; }
        render();
        notify(okMsg || 'TermMap: saved.');
      }).fail(function (code) {
        if (code === 'editconflict') { notify('TermMap: edit conflict — reloading.'); fetchAndRender(); }
        else { notify('TermMap: save failed — ' + code); }
      });
    }

    function setReview(rec, status, comment) {
      rec.review_status = status;
      rec.comment = comment;
      rec.reviewed_by = mw.config.get('wgUserName');
      rec.reviewed_at = nowIso();
    }

    function act(rec, status) {
      var verb = (status === 'validated') ? 'Validate' : 'Redo';
      var entered = window.prompt(verb + ' — why? (stored as the review comment)', rec.comment || '');
      if (entered === null) { return; }                 // cancelled
      entered = entered.replace(/^\s+|\s+$/g, '');
      if (!entered) { notify('TermMap: a comment is required.'); return; }
      setReview(rec, status, entered);
      save('TermMap: ' + verb.toLowerCase() + 'd.');
    }

    function btn(label, title, active, variant, handler) {
      var b = document.createElement('button');
      b.type = 'button'; b.textContent = label; b.title = title;
      b.className = 'rt-btn rt-btn--' + variant + (active ? ' is-active' : '');
      b.onclick = function (e) { e.preventDefault(); handler(); };
      return b;
    }
    function fill(cell, node) { if (cell) { cell.innerHTML = ''; cell.appendChild(node); } }

    function render() {
      if (!data) { return; }
      rows.forEach(function (r) {
        var rec = data[r.key];
        if (!rec) { return; }
        var status = rec.review_status || 'unreviewed';
        fill(r.vCell, btn('✓', status === 'validated' ? 'Validated — click to edit the comment' : 'Validate (with a reason)',
          status === 'validated', 'confirm', function () { act(rec, 'validated'); }));
        fill(r.rCell, btn('↻', status === 'redo' ? 'Marked redo — click to edit the comment' : 'Redo (with a reason)',
          status === 'redo', 'override', function () { act(rec, 'redo'); }));
        if (r.badge) {
          r.badge.className = 'rt-status rt-status-' + status;
          r.badge.textContent = (status === 'validated') ? '✓ validated' : (status === 'redo') ? '↻ redo' : 'unreviewed';
        }
        if (r.comment) { r.comment.textContent = rec.comment || ''; }
      });
    }

    collect();
    fetchAndRender();
  }, function (e) { mw.log('TermMap review: mediawiki.api failed to load', e); });
});


/* ── Hide level-6 headings from the sidebar (Vector) TOC ─────────────────────
   MediaWiki's TOC classes (vector-toc-level-N) encode only a COMPACTED nesting
   depth, NOT the original heading tag — when levels jump (h3->h6) it still only
   increments one level — so CSS cannot reliably target h6. Resolve each TOC
   entry to its body heading and hide the ones that are actually <h6>. Safe: it
   only ever hides h6 (never h2–h5). The mobile overlay excludes h6 separately
   (above). */
(function () {
  function headingFor(anchor) {
    if (!anchor) { return null; }
    var el = document.getElementById(anchor);
    if (!el) {
      try { el = document.getElementById(decodeURIComponent(anchor)); } catch (e) {}
    }
    if (!el) { return null; }
    if (el.matches && el.matches('h1,h2,h3,h4,h5,h6')) { return el; }
    return el.closest ? el.closest('h1,h2,h3,h4,h5,h6') : null;
  }
  function pruneTocH6() {
    var items = document.querySelectorAll('.vector-toc .vector-toc-list-item');
    Array.prototype.forEach.call(items, function (li) {
      var a = li.querySelector('a.vector-toc-link');
      if (!a) { return; }
      var href = a.getAttribute('href') || '';
      if (href.charAt(0) !== '#' || href.length < 2) { return; }
      var h = headingFor(href.slice(1));
      if (h && h.tagName === 'H6') { li.style.display = 'none'; }
    });
  }
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', pruneTocH6);
  } else {
    pruneTocH6();
  }
  // Vector can lazily (re)build the pinned TOC; re-run on its content hook.
  if (window.mw && mw.hook) { mw.hook('wikipage.content').add(pruneTocH6); }
})();