跳到正文
Novark

MediaWiki:Common.js

Phase1EmergencyAdmin​(留言 | 贡献)2026年10月25日 (日) 13:20的版本 (宽表布局:预览卡避开源词矩形,禁止遮住触发词)

注意:在发布之后,您可能需要清除浏览器缓存才能看到所作出的更改的影响。

  • Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5或Ctrl-R(Mac为⌘-R)
  • Google Chrome:按Ctrl-Shift-R(Mac为⌘-Shift-R)
  • Edge:按住Ctrl的同时单击刷新,或按Ctrl-F5。
/* Novark v2 功能组件:经济计算器、法术筛选/排序。
 * 自定义控件由本脚本创建;MediaWiki 正文不直接嵌入 input/select。
 * 数据/公式来自页面公开表格与旧站计算器的可视语义。 */
(function () {
  'use strict';

  function formatNumber(value) {
    if (!Number.isFinite(value)) return '—';
    return value.toLocaleString('zh-CN', { maximumFractionDigits: value >= 1000 ? 2 : 4 });
  }
  function num(value, fallback) {
    var n = Number(value);
    return Number.isFinite(n) ? n : fallback;
  }
  function optionText(selectEl) {
    return (selectEl && selectEl.selectedOptions && selectEl.selectedOptions[0] && selectEl.selectedOptions[0].textContent || '').trim();
  }
  function optionData(selectEl, key, fallback) {
    var o = selectEl && selectEl.selectedOptions && selectEl.selectedOptions[0];
    return num(o && o.dataset ? o.dataset[key] : undefined, fallback);
  }
  function el(tag, attrs, text) {
    var n = document.createElement(tag);
    if (attrs) Object.keys(attrs).forEach(function (k) { n.setAttribute(k, attrs[k]); });
    if (text !== undefined) n.textContent = text;
    return n;
  }
  function label(text, control) {
    var l = el('label', null, text + ' ');
    l.appendChild(control);
    return l;
  }
  function selectEl(id, values, selectedIndex) {
    var s = el('select', { id: id });
    values.forEach(function (v, i) {
      var o = el('option', null, v[0]);
      Object.keys(v[1] || {}).forEach(function (k) { o.dataset[k] = v[1][k]; });
      if (i === selectedIndex) o.selected = true;
      s.appendChild(o);
    });
    return s;
  }

  // 正文表格是系数和汇率的唯一来源;“—”表示该货币没有可用汇率。
  function economyNumber(text) {
    var parts = text.trim().split(/[((]/)[0].trim().split('/');
    return parts.length === 2 ? Number(parts[0]) / Number(parts[1]) : Number(parts[0]);
  }
  function economyRows(id) {
    var table = document.getElementById(id);
    if (!table) return [];
    return Array.prototype.slice.call(table.rows).filter(function (row) {
      return row.cells.length && row.cells[0].tagName === 'TD';
    }).map(function (row) {
      return Array.prototype.map.call(row.cells, function (cell) { return cell.textContent.trim(); });
    });
  }
  function readEconomyData() {
    return {
      alpha: economyRows('nv-economy-alpha').map(function (r) { return [r[0], { alpha: economyNumber(r[1]) }]; }),
      beta: economyRows('nv-economy-beta').map(function (r) { return [r[0], { beta: economyNumber(r[1]), limit: economyNumber(r[2]) }]; }),
      gamma: economyRows('nv-economy-gamma').map(function (r) { return [r[0], { gamma: economyNumber(r[1]) }]; }),
      currencies: economyRows('nv-economy-currencies').filter(function (r) {
        return economyNumber(r[1]) > 0 && economyNumber(r[2]) > 0;
      }).map(function (r) {
        return [r[0].split('/')[0], { rate: economyNumber(r[1]), marketRate: economyNumber(r[1]), nominalRate: economyNumber(r[2]) }];
      })
    };
  }

  function buildPriceUI(data) {
    var host = document.getElementById('mien-price-calculator');
    if (!host || host.dataset.built === 'true') return;
    host.dataset.built = 'true';
    host.innerHTML = '<div class="mien-price-calculator-title">价格计算器</div><div class="mien-price-calculator-row"></div>' +
      '<div class="mien-price-inline-result">结果:<strong id="mien-price-result">—</strong> <span id="mien-price-limit" class="mien-price-inline-limit"></span></div>' +
      '<div id="mien-price-formula" class="mien-price-formula-line"></div>';
    var row = host.querySelector('.mien-price-calculator-row');
    var base = el('input', { id: 'mien-price-base', type: 'number', min: '0', step: '0.01', value: '100' });
    var alpha = selectEl('mien-price-alpha', data.alpha, 0);
    var beta = selectEl('mien-price-beta', data.beta, data.beta.findIndex(function (v) { return v[0] === '普通'; }));
    var gamma = selectEl('mien-price-gamma', data.gamma, data.gamma.findIndex(function (v) { return v[0] === '普通'; }));
    var currency = selectEl('mien-price-currency', data.currencies, 0);
    row.appendChild(label('原价(GP)', base));
    row.appendChild(label('类型', alpha));
    row.appendChild(label('经济', beta));
    row.appendChild(label('技术', gamma));
    row.appendChild(label('货币', currency));

    function update() {
      var baseValue = num(base.value, 0);
      var a = optionData(alpha, 'alpha', 1);
      var b = optionData(beta, 'beta', 1);
      var g = optionData(gamma, 'gamma', 1);
      var rate = optionData(currency, 'rate', 1);
      var cap = optionData(beta, 'limit', 0);
      var gp = baseValue * a * b * g;
      var finalPrice = gp * rate;
      var currencyName = optionText(currency);
      host.querySelector('#mien-price-result').textContent = formatNumber(finalPrice) + ' ' + currencyName + '(' + formatNumber(gp) + ' GP)';
      var limit = host.querySelector('#mien-price-limit');
      limit.classList.remove('mien-price-limit-ok', 'mien-price-limit-over');
      if (gp <= cap) { limit.textContent = '限额 ' + formatNumber(cap) + ' GP:可交易'; limit.classList.add('mien-price-limit-ok'); }
      else { limit.textContent = '限额 ' + formatNumber(cap) + ' GP:需 DM 裁定'; limit.classList.add('mien-price-limit-over'); }
      host.querySelector('#mien-price-formula').textContent =
        '实际价值:ω* = ω0 × α × β × γ = ' + formatNumber(baseValue) + ' GP × ' + a + ' × ' + b + ' × ' + g +
        ' = ' + formatNumber(gp) + ' GP。结算价格:ω = ω* × δ* = ' + formatNumber(gp) + ' GP × ' + rate +
        ' = ' + formatNumber(finalPrice) + ' ' + currencyName + '。';
    }
    [base, alpha, beta, gamma, currency].forEach(function (c) {
      c.addEventListener('input', update);
      c.addEventListener('change', update);
    });
    update();
  }

  function buildCreditUI(data) {
    var host = document.getElementById('mien-credit-currency-calculator');
    if (!host || host.dataset.built === 'true') return;
    host.dataset.built = 'true';
    host.innerHTML = '<div class="mien-currency-calculator-title">汇率计算器</div><div class="mien-currency-calculator-row"></div>' +
      '<div class="mien-currency-inline-result">结果:<strong id="mien-credit-result">—</strong></div>' +
      '<div class="mien-currency-inline-result">名义等值:<strong id="mien-credit-nominal-result">—</strong> GP;市场等值:<strong id="mien-credit-market-result">—</strong> GP</div>' +
      '<div id="mien-credit-formula" class="mien-price-formula-line"></div>';
    var row = host.querySelector('.mien-currency-calculator-row');
    var amount = el('input', { id: 'mien-credit-amount', type: 'number', min: '0', step: '0.01', value: '100' });
    var source = selectEl('mien-credit-source', data.currencies, 0);
    var target = selectEl('mien-credit-target', data.currencies, data.currencies.findIndex(function (v) { return v[0] === '帝国币'; }));
    row.appendChild(label('金额', amount));
    row.appendChild(label('源货币', source));
    row.appendChild(label('目标货币', target));
    host.appendChild(el('p', null, '选项来自下方货币表;未标明汇率的独立本位币不参与换算。'));

    function currencyName(selectItem) {
      var text = optionText(selectItem);
      return text.indexOf('|') !== -1 ? text.split('|')[1].trim() : text;
    }
    function update() {
      var value = num(amount.value, 0);
      var sn = optionData(source, 'nominalRate', 1);
      var sm = optionData(source, 'marketRate', sn);
      var tn = optionData(target, 'nominalRate', 1);
      var tm = optionData(target, 'marketRate', tn);
      var snGp = value / sn, smGp = value / sm;
      var targetAmount = smGp * tn, targetMarket = smGp * tm;
      host.querySelector('#mien-credit-result').textContent = formatNumber(targetAmount) + ' ' + currencyName(target);
      host.querySelector('#mien-credit-nominal-result').textContent = formatNumber(snGp);
      host.querySelector('#mien-credit-market-result').textContent = formatNumber(smGp);
      host.querySelector('#mien-credit-formula').textContent =
        '源货币名义等值:' + formatNumber(value) + ' ' + currencyName(source) + ' ÷ ' + sn + ' = ' + formatNumber(snGp) + ' GP。' +
        '源货币市场折算:' + formatNumber(value) + ' ' + currencyName(source) + ' ÷ ' + sm + ' = ' + formatNumber(smGp) + ' GP。' +
        '目标货币结算:' + formatNumber(smGp) + ' GP × ' + tn + ' = ' + formatNumber(targetAmount) + ' ' + currencyName(target) + '。' +
        '市场参考:' + formatNumber(smGp) + ' GP × ' + tm + ' = ' + formatNumber(targetMarket) + ' ' + currencyName(target) + '。';
    }
    [amount, source, target].forEach(function (c) { c.addEventListener('input', update); c.addEventListener('change', update); });
    update();
  }

  function spellNoValue(value) {
    var v = String(value || '').trim();
    return (v === '' || v === '-' || v === '—' || v === '无') ? '无' : v;
  }
  function uniqueValues(values) {
    var seen = {};
    return values.filter(function (v) {
      if (!v || seen[v]) return false;
      seen[v] = true;
      return true;
    });
  }
  function buildSpellUI() {
    var host = document.getElementById('spell-filter-host');
    var table = document.querySelector('.mien-spell-table');
    if (!host || !table || host.dataset.built === 'true') return;
    host.dataset.built = 'true';
    host.className = 'mien-spell-filter';
    var rows = spellRows(table);
    var classes = uniqueValues(rows.reduce(function (values, row) {
      var value = spellNoValue(cellText(row, 3));
      return values.concat([value], value.split(/[\/、,,]/).map(function (v) { return v.trim(); }));
    }, []));
    var levels = uniqueValues(rows.map(function (row) { return cellText(row, 1).replace(/\s*级$/, '').trim(); })).sort(function (a, b) { return Number(a) - Number(b); });
    var schools = uniqueValues(rows.map(function (row) { return cellText(row, 2); }));
    var domains = uniqueValues(rows.map(function (row) {
      var value = spellNoValue(cellText(row, 4));
      return value === '无' ? '—' : value;
    }));
    var search = el('input', { id: 'spell-search', type: 'search', placeholder: '搜索法术名称、简述、学派…', 'aria-label': '搜索法术' });
    var klass = el('select', { id: 'spell-class-filter', 'aria-label': '法表' });
    [''].concat(classes).forEach(function (v) { klass.appendChild(el('option', { value: v }, v === '' ? '全部法表' : v)); });
    var level = el('select', { id: 'spell-level-filter', 'aria-label': '等级' });
    [''].concat(levels).forEach(function (v) { level.appendChild(el('option', { value: v }, v === '' ? '全部等级' : v + ' 级')); });
    var school = el('select', { id: 'spell-school-filter', 'aria-label': '学派' });
    [''].concat(schools).forEach(function (v) { school.appendChild(el('option', { value: v }, v === '' ? '全部学派' : v)); });
    var domain = el('select', { id: 'spell-domain-filter', 'aria-label': '领域' });
    [''].concat(domains).forEach(function (v) { domain.appendChild(el('option', { value: v }, v === '' ? '全部领域' : (v === '—' ? '无领域' : v))); });
    var clear = el('button', { type: 'button', id: 'spell-clear' }, '清除条件');
    [search, klass, level, school, domain, clear].forEach(function (n) { host.appendChild(n); });
  }

  function spellRows(table) {
    return Array.prototype.slice.call(table.querySelectorAll('tbody tr')).filter(function (row) { return row.cells && row.cells[0] && row.cells[0].tagName === 'TD'; });
  }
  function cellText(row, index) {
    var cell = row.cells && row.cells[index];
    return cell ? cell.textContent.trim() : '';
  }
  function applySpellFilters(table) {
    var search = document.getElementById('spell-search');
    var classFilter = document.getElementById('spell-class-filter');
    var levelFilter = document.getElementById('spell-level-filter');
    var schoolFilter = document.getElementById('spell-school-filter');
    var domainFilter = document.getElementById('spell-domain-filter');
    var searchValue = (search && search.value || '').trim().toLowerCase();
    var classValue = classFilter && classFilter.value || '';
    var levelValue = levelFilter && levelFilter.value || '';
    var schoolValue = schoolFilter && schoolFilter.value || '';
    var domainValue = domainFilter && domainFilter.value || '';
    spellRows(table).forEach(function (row) {
      var cells = Array.prototype.map.call(row.cells, function (cell) { return cell.textContent.trim(); });
      var rowClass = spellNoValue(cellText(row, 3));
      var rowLevel = cellText(row, 1).replace(/\s*级$/, '').trim();
      var rowSchool = cellText(row, 2);
      var rowDomain = cellText(row, 4);
      var matches = (!searchValue || cells.join(' ').toLowerCase().indexOf(searchValue) !== -1) &&
        (!classValue || rowClass.indexOf(classValue) !== -1) &&
        (!levelValue || rowLevel === levelValue) &&
        (!schoolValue || rowSchool === schoolValue) &&
        (!domainValue || (domainValue === '—' ? (rowDomain === '—' || rowDomain === '-' || rowDomain === '') : rowDomain === domainValue));
      row.hidden = !matches;
      row.classList.toggle('mien-spell-row-hidden', !matches);
    });
  }
  function sortSpellTable(table, headerIndex, ascending) {
    var tbody = table.tBodies[0];
    if (!tbody) return;
    var headRow = (table.tHead && table.tHead.rows[0]) || table.rows[0];
    var header = headRow ? headRow.cells[headerIndex] : null;
    var numeric = header ? header.textContent.indexOf('等级') !== -1 : false;
    spellRows(table).sort(function (a, b) {
      var av = cellText(a, headerIndex), bv = cellText(b, headerIndex);
      var cmp = numeric ? num(av.replace(/\s*级$/, ''), 0) - num(bv.replace(/\s*级$/, ''), 0) : av.localeCompare(bv, 'zh-Hans-CN');
      return ascending ? cmp : -cmp;
    }).forEach(function (row) { tbody.appendChild(row); });
    applySpellFilters(table);
  }
  function bindSpellTable() {
    var table = document.querySelector('.mien-spell-table');
    if (!table || table.dataset.mienSpellInitialized === 'true') return;
    table.dataset.mienSpellInitialized = 'true';
    ['spell-search', 'spell-class-filter', 'spell-level-filter', 'spell-school-filter', 'spell-domain-filter'].forEach(function (id) {
      var control = document.getElementById(id);
      if (!control) return;
      control.addEventListener('input', function () { applySpellFilters(table); });
      control.addEventListener('change', function () { applySpellFilters(table); });
    });
    var clear = document.getElementById('spell-clear');
    if (clear) clear.addEventListener('click', function () {
      ['spell-search', 'spell-class-filter', 'spell-level-filter', 'spell-school-filter', 'spell-domain-filter'].forEach(function (id) {
        var control = document.getElementById(id);
        if (control) control.value = '';
      });
      applySpellFilters(table);
    });
    var headRow = (table.tHead && table.tHead.rows[0]) || table.rows[0];
    if (headRow) {
      Array.prototype.forEach.call(headRow.cells, function (th, index) {
        th.style.cursor = 'pointer';
        th.title = '点击按此列排序';
        th.addEventListener('click', function () {
          var ascending = th.getAttribute('data-sort-direction') !== 'asc';
          Array.prototype.forEach.call(headRow.cells, function (h) { h.removeAttribute('data-sort-direction'); });
          th.setAttribute('data-sort-direction', ascending ? 'asc' : 'desc');
          sortSpellTable(table, index, ascending);
        });
      });
    }
    applySpellFilters(table);
  }

  function init() {
    if (document.getElementById('mien-price-calculator') || document.getElementById('mien-credit-currency-calculator')) {
      var economy = readEconomyData();
      if (economy.alpha.length && economy.beta.length && economy.gamma.length && economy.currencies.length) {
        buildPriceUI(economy);
        buildCreditUI(economy);
      } else {
        ['mien-price-calculator', 'mien-credit-currency-calculator'].forEach(function (id) {
          var host = document.getElementById(id);
          if (host) host.textContent = '计算器需要本页完整的物价系数表和货币汇率表。';
        });
      }
    }
    buildSpellUI();
    bindSpellTable();
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
  else init();
  if (window.mw && mw.hook) mw.hook('wikipage.content').add(init);
}());

/* ==========================================================================
   弥恩 Wiki 交互层 v2 · mien-interaction-v2.js
   ---------------------------------------------------------------------------
   相对 v1 的改动(对应 03 审阅修正点,详见《全局设计规范-v2.md》§7):
   03-1 站上无 Gadgets:本文件放 MediaWiki:Common.js;用 mw.loader.using
        等 mediawiki.user / mediawiki.util 就绪后再初始化。
   03-2 搜索:生产 Citizen 搜索是原生 form,无动态结果浮层;本文件不再维护
        第二套搜索面板,回车/按钮走 MediaWiki 原生搜索页。
   03-3 导航等待仅限 body.action-view 阅读页;click 与 submit 同等排除
        OOUI、PageForms、术语编辑器;编辑/预览/保存/特殊页不显示等待线。
   03-4 空页/搜索无结果只用生产静态几何,不在 JS 再造 SVG。
   03-6 theme-color 切换后读取 body 计算样式回写,单一颜色来源;
        html class 观察做字符串去抖。
   已核实并内置:主题类 skin-theme-clientpref-{day|night|os}、
   浮动标题 #citizen-sticky-header;搜索走原生 MediaWiki 表单。
   语法 ES2017。
   ========================================================================== */
( function () {
	'use strict';

	function init() {
		var CFG = Object.assign( {
			themePrefKey: 'skin-theme',
			themeValues: { day: 'day', night: 'night', os: 'os' },

			/* 已核实的 DOM */
			stickyHeader: '#citizen-sticky-header',

			/* 日夜按钮挂载:二选一。mw-portlet-personal 在生产 DOM 存在;
			   具体放哪由 DS 定,两项都空则不显示按钮(API 仍可调用) */
			themeToggleMount: null,
			themeTogglePortlet: 'p-personal',
			themeToggleCompact: true,

			navPendingDelay: 120,
			navPendingTimeout: 8000
		}, window.MienInteractionConfig || {} );

		var html = document.documentElement;
		var isReadingPage = document.body && document.body.classList.contains( 'action-view' ) &&
			!document.body.classList.contains( 'ns-special' );
		var reduced = function () {
			return window.matchMedia && window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches;
		};
		var qsa = function ( sel, root ) {
			return sel ? Array.prototype.slice.call( ( root || document ).querySelectorAll( sel ) ) : [];
		};
		var esc = function ( s ) { return String( s ).replace( /[.*+?^${}()|[\]\\]/g, '\\$&' ); };

		/* ==================== 1. 日夜切换 ==================== */
		function prefs() {
			return ( window.mw && mw.user && mw.user.clientPrefs ) ? mw.user.clientPrefs : null;
		}
		function currentPref() {
			var cp = prefs();
			if ( cp && typeof cp.get === 'function' ) {
				try { var v = cp.get( CFG.themePrefKey ); if ( v ) { return v; } } catch ( e ) {}
			}
			var m = html.className.match( new RegExp( '(?:^|\\s)' + esc( CFG.themePrefKey ) + '-clientpref-(\\S+)' ) );
			return m ? m[ 1 ] : null;
		}
		function isNight() {
			var p = currentPref();
			if ( p === CFG.themeValues.night ) { return true; }
			if ( p === CFG.themeValues.day ) { return false; }
			return !!( window.matchMedia && window.matchMedia( '(prefers-color-scheme: dark)' ).matches );
		}
		function syncThemeUi() {
			var night = isNight();
			qsa( '.mien-theme-toggle' ).forEach( function ( b ) {
				b.setAttribute( 'aria-pressed', night ? 'true' : 'false' );
				var label = night ? '切换到日间模式' : '切换到夜间模式';
				b.title = label;
				b.setAttribute( 'aria-label', label );
				var l = b.querySelector( '.mien-theme-toggle__label' );
				if ( l ) { l.textContent = night ? '日间' : '夜间'; }
			} );
			/* 03-6:单一颜色来源——读静态层算出的实际纸色回写 meta */
			var meta = document.querySelector( 'meta[name="theme-color"]' );
			if ( meta && document.body ) {
				var bg = getComputedStyle( document.body ).backgroundColor;
				if ( bg && bg !== 'rgba(0, 0, 0, 0)' ) { meta.setAttribute( 'content', bg ); }
			}
		}
		function setTheme( value ) {
			var cp = prefs();
			if ( !cp || typeof cp.set !== 'function' ) { return false; }
			var apply = function () { cp.set( CFG.themePrefKey, value ); syncThemeUi(); };
			if ( document.startViewTransition && !reduced() ) {
				var done = function () { html.classList.remove( 'mien-vt-theme' ); };
				html.classList.add( 'mien-vt-theme' );
				try {
					document.startViewTransition( apply ).finished.then( done, done );
				} catch ( e ) { done(); apply(); }
			} else {
				apply();
			}
			return true;
		}
		function toggleTheme() {
			return setTheme( isNight() ? CFG.themeValues.day : CFG.themeValues.night );
		}
		function makeToggle() {
			var b = document.createElement( 'button' );
			b.type = 'button';
			b.className = 'mien-theme-toggle' + ( CFG.themeToggleCompact ? ' mien-theme-toggle--compact' : '' );
			b.innerHTML = '<span class="mien-theme-toggle__icon" aria-hidden="true"></span><span class="mien-theme-toggle__label"></span>';
			b.addEventListener( 'click', function ( e ) { e.preventDefault(); toggleTheme(); } );
			return b;
		}
		function mountToggle() {
			if ( !prefs() || document.querySelector( '.mien-theme-toggle' ) ) { return; }
			var host = CFG.themeToggleMount && document.querySelector( CFG.themeToggleMount );
			if ( host ) {
				host.appendChild( makeToggle() );
			} else if ( CFG.themeTogglePortlet && window.mw && mw.util && mw.util.addPortletLink ) {
				var li = mw.util.addPortletLink( CFG.themeTogglePortlet, '#', '夜间', 'mien-theme-toggle-item' );
				if ( li ) {
					var a = li.querySelector( 'a' );
					var b = makeToggle();
					if ( a ) { a.replaceWith( b ); } else { li.appendChild( b ); }
				}
			}
			syncThemeUi();
		}
		/* 03-6:去抖——class 字符串没变就不重复处理 */
		var lastHtmlClass = html.className;
		new MutationObserver( function () {
			if ( html.className === lastHtmlClass ) { return; }
			lastHtmlClass = html.className;
			syncThemeUi();
		} ).observe( html, { attributes: true, attributeFilter: [ 'class' ] } );
		if ( window.matchMedia ) {
			var mq = window.matchMedia( '(prefers-color-scheme: dark)' );
			if ( mq.addEventListener ) { mq.addEventListener( 'change', syncThemeUi ); }
		}

		/* ==================== 2. 导航反馈(仅阅读页,03-3) ==================== */
		var pendingTimer = 0, pendingGuard = 0;
		function clearPending() {
			clearTimeout( pendingTimer ); clearTimeout( pendingGuard );
			html.classList.remove( 'mien-nav-pending' );
		}
		function showPending() {
			html.classList.add( 'mien-nav-pending' );
			clearTimeout( pendingGuard );
			pendingGuard = setTimeout( clearPending, CFG.navPendingTimeout );
		}
		/* click 与 submit 共用的排除区(03-3:两者同等排除) */
		var EXCLUDE_ZONE = '[data-mien-nav="off"], .nv-glossary-index, .nv-term-library, #nv-term-editor, .oo-ui-widget, .pfForm, .author-entry-form, .mien-spell-filter, .mien-price-inline-calculator, .mien-currency-inline-calculator';
		function willNavigateSameTab( e, a ) {
			if ( e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey ) { return false; }
			if ( a.target && a.target !== '_self' ) { return false; }
			if ( a.hasAttribute( 'download' ) || a.getAttribute( 'role' ) === 'button' ) { return false; }
			if ( a.closest( EXCLUDE_ZONE ) ) { return false; }
			var raw = a.getAttribute( 'href' ) || '';
			if ( !raw || raw.charAt( 0 ) === '#' || /^(javascript|mailto|tel):/i.test( raw ) ) { return false; }
			var u;
			try { u = new URL( a.href, location.href ); } catch ( err ) { return false; }
			if ( u.origin !== location.origin ) { return false; }
			if ( u.pathname === location.pathname && u.search === location.search ) { return false; }
			/* 去往编辑/提交动作的链接不显示等待线(点红链直达编辑器属原生行为) */
			if ( /[?&]action=(edit|submit|formedit)\b/.test( u.search ) ) { return false; }
			return true;
		}
		if ( isReadingPage ) {
			document.addEventListener( 'click', function ( e ) {
				var a = e.target && e.target.closest ? e.target.closest( 'a[href]' ) : null;
				if ( !a || e.defaultPrevented || !willNavigateSameTab( e, a ) ) { return; }
				clearTimeout( pendingTimer );
				pendingTimer = setTimeout( function () { if ( !e.defaultPrevented ) { showPending(); } }, CFG.navPendingDelay );
			} );
			document.addEventListener( 'submit', function ( e ) {
				var f = e.target;
				if ( !f || ( f.target && f.target !== '_self' ) ) { return; }
				if ( f.closest( EXCLUDE_ZONE ) ) { return; } /* 03-3:submit 同等排除 */
				clearTimeout( pendingTimer );
				pendingTimer = setTimeout( function () { if ( !e.defaultPrevented ) { showPending(); } }, CFG.navPendingDelay );
			} );
		}
		window.addEventListener( 'pageshow', clearPending );
		window.addEventListener( 'pagehide', function () { clearTimeout( pendingTimer ); } );

		/* ==================== 3. 锚点偏移 ==================== */
		function syncStickyOffset() {
			var el = CFG.stickyHeader && document.querySelector( CFG.stickyHeader );
			if ( el ) { html.style.setProperty( '--mien-sticky-offset', ( el.getBoundingClientRect().height + 16 ) + 'px' ); }
		}

		/* ==================== 启动 ==================== */
		function refresh() {
			mountToggle();
			syncStickyOffset();
		}
		window.MienInteraction = {
			version: '2.0.0',
			config: CFG,
			toggleTheme: toggleTheme,
			setTheme: setTheme,
			isNight: isNight,
			refresh: refresh,
			_showPending: showPending,
			_clearPending: clearPending
		};
		refresh();
		window.addEventListener( 'resize', syncStickyOffset, { passive: true } );
	}

	/* 03-1:等依赖就绪再初始化(Common.js 环境必有 mw.loader) */
	if ( window.mw && mw.loader && mw.loader.using ) {
		mw.loader.using( [ 'mediawiki.user', 'mediawiki.util' ] ).then( function () {
			if ( document.readyState === 'loading' ) {
				document.addEventListener( 'DOMContentLoaded', init );
			} else {
				init();
			}
		} );
	} else if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', init ); /* 本地演示用回退 */
	} else {
		init();
	}
}() );

/* ==========================================================================
   nv-lock.js · 渐进锁定阅读链
   - 真实 800ms 进度;满圈才 locked,可移入
   - 根词 180ms 延迟;未满圈离开立即取消
   - 每层以当次触发鼠标坐标为锚,不排队
   - 无深度上限;窄屏单面板可继续深入
   ========================================================================== */
( function () {
	'use strict';

	function boot() {
		if ( window.NvLock ) { return; }

		var CFG = {
			rootDelay: 180,
			childDelay: 170,
			lockMs: 800,
			gap: 10,
			width: 352,
			grace: 120
		};
		var reduceMotion = window.matchMedia && window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches;
		var coarse = window.matchMedia && window.matchMedia( '(hover: none), (pointer: coarse)' ).matches;
		var pageName = ( mw.config && mw.config.get( 'wgPageName' ) ) || '';
		var mainPage = !! ( mw.config && mw.config.get( 'wgIsMainPage' ) ) || pageName === '首页';
		var termLibraryPage = pageName === '术语库';
		var termIndex = null;
		var termLoading = null;
		var state = {
			source: null,
			pendingSource: null,
			stack: [],
			pointer: { x: 0, y: 0 },
			pendingRoot: 0,
			pendingChild: 0,
			closeAllTimer: 0,
			closeChildTimer: 0,
			closeChildIndex: -1,
			suppressClickUntil: 0,
			single: false
		};

		function clearTimer( key ) {
			if ( state[ key ] ) { clearTimeout( state[ key ] ); state[ key ] = 0; }
		}
		function closest( el, sel ) { return el && el.closest ? el.closest( sel ) : null; }
		function norm( s ) {
			return String( s || '' ).replace( /_/g, ' ' ).replace( /\s+/g, ' ' ).trim().toLowerCase();
		}
		function termHref( term ) {
			if ( term.article ) { return mw.util.getUrl( term.article ); }
			return mw.util.getUrl( '术语库' ) + '#' + term.id;
		}
		function targetOf( a ) {
			if ( !a || !a.getAttribute ) { return null; }
			var raw = a.getAttribute( 'href' ) || '';
			if ( !raw || raw.charAt( 0 ) === '#' || /^(javascript|mailto|tel):/i.test( raw ) ) { return null; }
			var url;
			try { url = new URL( a.href, location.href ); } catch ( e ) { return null; }
			if ( url.origin !== location.origin ) { return null; }
			var action = url.searchParams.get( 'action' );
			if ( action && action !== 'view' ) { return null; }
			if ( url.searchParams.get( 'redlink' ) || url.searchParams.get( 'oldid' ) || url.searchParams.get( 'diff' ) ) { return null; }
			var title = null;
			if ( url.pathname.indexOf( '/wiki/' ) === 0 ) {
				try { title = decodeURIComponent( url.pathname.slice( 6 ) ); } catch ( e ) {}
			} else if ( url.searchParams.get( 'title' ) ) {
				title = url.searchParams.get( 'title' );
			}
			if ( !title ) { return null; }
			title = title.replace( /_/g, ' ' ).trim();
			if ( /^(Special|File|Category|MediaWiki|Module|Template):/i.test( title ) ) { return null; }
			return { title: title, hash: url.hash ? decodeURIComponent( url.hash.slice( 1 ) ) : '' };
		}
		function isReference( a ) {
			return !! closest( a, 'sup.reference, .reference, [role="doc-noteref"], .mw-cite-backlink, .references a' );
		}
		function isBody( a ) { return !! closest( a, '.mw-parser-output' ); }
		function isCard( el ) { return !! closest( el, '.nv-lock' ); }

		function fetchTerms() {
			if ( termIndex ) { return Promise.resolve( termIndex ); }
			if ( termLoading ) { return termLoading; }
			var url = mw.util.getUrl( 'Module:术语库/data.json', { action: 'raw' } );
			termLoading = fetch( url, { credentials: 'same-origin' } ).then( function ( r ) {
				if ( !r.ok ) { throw new Error( 'terms-' + r.status ); }
				return r.json();
			} ).then( function ( data ) {
				var byId = Object.create( null );
				var byTitle = Object.create( null );
				var unique = Object.create( null );
				( data.terms || [] ).forEach( function ( t ) {
					byId[ t.id ] = t;
					[ t.name ].concat( t.aliases || [] ).forEach( function ( n ) {
						var key = norm( n );
						if ( !key ) { return; }
						byTitle[ key ] = t;
						if ( unique[ key ] && unique[ key ].id !== t.id ) { unique[ key ] = null; }
						else { unique[ key ] = t; }
					} );
				} );
				termIndex = { byId: byId, byTitle: byTitle, unique: unique, raw: data };
				return termIndex;
			} ).catch( function ( err ) {
				termLoading = null;
				throw err;
			} );
			return termLoading;
		}

		function termFromAnchor( a ) {
			if ( !a || a.closest( '.nv-lock' ) || a.classList.contains( 'new' ) ) { return null; }
			var target = targetOf( a );
			if ( !target ) { return null; }
			var ref = closest( a, '.nv-term-ref' );
			var id = null;
			if ( ref ) { id = ( target.hash.match( /^term-\d+$/ ) || [] )[ 0 ] || null; }
			else if ( target.title === '术语库' ) { id = ( target.hash.match( /^term-\d+$/ ) || [] )[ 0 ] || null; }
			if ( id ) {
				if ( !termIndex ) { return null; }
				return termIndex.byId[ id ] ? { id: id, term: termIndex.byId[ id ] } : null;
			}
			if ( !termIndex ) { return null; }
			var term = termIndex.byTitle[ norm( target.title ) ];
			return term ? { id: term.id, term: term } : null;
		}

		function potentialTermAnchor( a ) {
			var target = targetOf( a );
			if ( ! target ) { return false; }
			if ( a.closest( '.nv-term-ref' ) ) { return /^term-\d+$/.test( target.hash ); }
			return target.title === '术语库' && /^term-\d+$/.test( target.hash );
		}

		function linkify( text, currentId ) {
			if ( !termIndex || !text ) {
				var p = document.createDocumentFragment();
				p.appendChild( document.createTextNode( text || '' ) );
				return p;
			}
			var keys = Object.keys( termIndex.unique ).filter( function ( k ) {
				return !!termIndex.unique[ k ] && termIndex.unique[ k ].id !== currentId;
			} ).sort( function ( a, b ) { return b.length - a.length; } );
			var frag = document.createDocumentFragment();
			var lower = String( text ).toLowerCase();
			var i = 0, buf = '';
			while ( i < text.length ) {
				var hit = null, hitKey = '';
				for ( var k = 0; k < keys.length; k++ ) {
					var key = keys[ k ];
					if ( key.length > hitKey.length && lower.substr( i, key.length ) === key ) {
						hit = termIndex.unique[ key ];
						hitKey = key;
					}
				}
				if ( hit ) {
					if ( buf ) { frag.appendChild( document.createTextNode( buf ) ); buf = ''; }
					var a = document.createElement( 'a' );
					a.className = 'nv-lock__term-link';
					a.href = mw.util.getUrl( '术语库' ) + '#' + hit.id;
					a.setAttribute( 'data-term-id', hit.id );
					a.title = hit.name;
					a.textContent = text.substr( i, hitKey.length );
					frag.appendChild( a );
					i += hitKey.length;
				} else {
					buf += text.charAt( i++ );
				}
			}
			if ( buf ) { frag.appendChild( document.createTextNode( buf ) ); }
			return frag;
		}

		function pointFromLink( a ) {
			var r = a.getBoundingClientRect();
			return {
				x: Math.min( window.innerWidth - 8, Math.max( 8, r.left + r.width / 2 ) ),
				y: Math.min( window.innerHeight - 8, Math.max( 8, r.top + r.height / 2 ) )
			};
		}
		function anchorPoint( a ) {
			if ( state.pointer.x || state.pointer.y ) { return { x: state.pointer.x, y: state.pointer.y }; }
			return pointFromLink( a );
		}

		function makeCard( layer ) {
			var card = document.createElement( 'div' );
			card.className = 'nv-lock';
			card.setAttribute( 'role', 'dialog' );
			card.setAttribute( 'aria-label', layer.term.name + ' 术语短卡' );
			card.setAttribute( 'data-depth', String( layer.depth ) );
			card.innerHTML =
				'<div class="nv-lock__header">' +
					'<button type="button" class="nv-lock__back" aria-label="返回上一层" title="返回上一层" hidden>←</button>' +
					'<a class="nv-lock__title" href="#"></a>' +
					'<svg class="nv-lock__ring" viewBox="0 0 16 16" aria-hidden="true">' +
						'<circle class="nv-lock__ring-track" cx="8" cy="8" r="6.4"></circle>' +
						'<circle class="nv-lock__ring-arc" cx="8" cy="8" r="6.4"></circle>' +
					'</svg>' +
				'</div>' +
				'<div class="nv-lock__body"><p class="nv-lock__definition"></p></div>';
			var title = card.querySelector( '.nv-lock__title' );
			title.href = termHref( layer.term );
			title.textContent = layer.term.name;
			card.querySelector( '.nv-lock__definition' ).appendChild( linkify( layer.term.definition || '', layer.term.id ) );
			var back = card.querySelector( '.nv-lock__back' );
			back.addEventListener( 'click', function ( e ) {
				e.preventDefault();
				e.stopPropagation();
				backOne();
			} );
			card.addEventListener( 'mouseenter', function () {
				clearTimer( 'closeAllTimer' );
				clearTimer( 'closeChildTimer' );
			} );
			card.addEventListener( 'mouseleave', function ( e ) { onCardLeave( layer, e ); } );
			card.addEventListener( 'mouseover', function ( e ) { onCardOver( layer, e ); } );
			card.addEventListener( 'mouseout', function ( e ) { onCardOut( layer, e ); } );
			card.addEventListener( 'click', function ( e ) { onCardClick( layer, e ); } );
			card.addEventListener( 'touchstart', function ( e ) { e.stopPropagation(); }, true );
			layer.el = card;
			layer.ring = card.querySelector( '.nv-lock__ring-arc' );
			return card;
		}

		function setRing( layer, p ) {
			if ( !layer.ring ) { return; }
			layer.progress = p;
			layer.ring.style.strokeDashoffset = String( 40.21 * ( 1 - p ) );
			if ( p >= 1 ) { layer.el.setAttribute( 'data-locked', 'true' ); }
		}
		function completeRing( layer ) {
			if ( layer.raf ) { cancelAnimationFrame( layer.raf ); layer.raf = 0; }
			layer.locked = true;
			setRing( layer, 1 );
		}
		function startRing( layer ) {
			if ( reduceMotion ) { completeRing( layer ); return; }
			layer.locked = false;
			layer.startedAt = performance.now();
			var tick = function ( now ) {
				var p = Math.min( 1, ( now - layer.startedAt ) / CFG.lockMs );
				setRing( layer, p );
				if ( p >= 1 ) {
					layer.locked = true;
					layer.raf = 0;
					return;
				}
				layer.raf = requestAnimationFrame( tick );
			};
			layer.raf = requestAnimationFrame( tick );
		}

		function positionLayer( layer ) {
			var card = layer.el;
			var w = card.offsetWidth || Math.min( CFG.width, window.innerWidth - 24 );
			var h = card.offsetHeight || 180;
			var vw = window.innerWidth, vh = window.innerHeight;
			var ax = layer.anchor.x, ay = layer.anchor.y;
			var g = CFG.gap;
			var candidates = [
				{ l: ax + g, t: ay - 28 },
				{ l: ax - w - g, t: ay - 28 },
				{ l: ax + g, t: ay - h - g },
				{ l: ax - w - g, t: ay - h - g },
				{ l: ax - w / 2, t: ay + g },
				{ l: ax - w / 2, t: ay - h - g }
			];
			var src = layer.sourceLink ? layer.sourceLink.getBoundingClientRect() : null;
			function overlapsSource( l, t ) {
				return !! src && ! ( l + w <= src.left || l >= src.right || t + h <= src.top || t >= src.bottom );
			}
			var chosen = null;
			for ( var i = 0; i < candidates.length; i++ ) {
				var l = Math.max( 8, Math.min( candidates[ i ].l, vw - w - 8 ) );
				var t = Math.max( 8, Math.min( candidates[ i ].t, vh - h - 8 ) );
				if ( ax >= l && ax <= l + w && ay >= t && ay <= t + h ) { continue; }
				if ( overlapsSource( l, t ) ) { continue; }
				chosen = { l: l, t: t };
				break;
			}
			if ( !chosen && src ) {
				var preferred = [
					{ l: src.right + g, t: ay - 28 },
					{ l: src.left - w - g, t: ay - 28 },
					{ l: ax + g, t: src.bottom + g },
					{ l: ax - w - g, t: src.bottom + g }
				];
				for ( var j = 0; j < preferred.length; j++ ) {
					var cl = Math.max( 8, Math.min( preferred[ j ].l, vw - w - 8 ) );
					var ct = Math.max( 8, Math.min( preferred[ j ].t, vh - h - 8 ) );
					if ( ax >= cl && ax <= cl + w && ay >= ct && ay <= ct + h ) { continue; }
					if ( overlapsSource( cl, ct ) ) { continue; }
					chosen = { l: cl, t: ct };
					break;
				}
			}
			if ( !chosen ) {
				chosen = {
					l: Math.max( 8, Math.min( ax + g, vw - w - 8 ) ),
					t: Math.max( 8, Math.min( ay - 28, vh - h - 8 ) )
				};
			}
			card.style.width = Math.min( CFG.width, vw - 24 ) + 'px';
			card.style.left = chosen.l + 'px';
			card.style.top = chosen.t + 'px';
			card.style.zIndex = String( 1200 + layer.depth * 10 );
			layer.bounds = { left: chosen.l, top: chosen.t, width: w, height: h };
		}

		function applyVisibility() {
			state.single = window.matchMedia( '(max-width: 720px)' ).matches;
			var top = state.stack[ state.stack.length - 1 ];
			state.stack.forEach( function ( layer, i ) {
				var visible = ! state.single || i === state.stack.length - 1;
				layer.el.style.display = visible ? 'flex' : 'none';
				layer.el.classList.toggle( 'nv-lock--single', state.single );
				layer.el.querySelector( '.nv-lock__back' ).hidden = ! state.single || state.stack.length < 2;
			} );
			if ( top ) {
				top.el.setAttribute( 'aria-modal', state.single ? 'true' : 'false' );
			}
		}

		function createLayer( term, depth, anchor, sourceLink, locked ) {
			var layer = {
				term: term,
				depth: depth,
				anchor: { x: anchor.x, y: anchor.y },
				sourceLink: sourceLink || null,
				locked: !! locked,
				progress: 0,
				raf: 0,
				el: null,
				ring: null
			};
			var card = makeCard( layer );
			state.stack.push( layer );
			document.body.appendChild( card );
			positionLayer( layer );
			applyVisibility();
			if ( locked ) { completeRing( layer ); }
			else { startRing( layer ); }
			return layer;
		}

		function removeFrom( index, keepSource ) {
			if ( index < 0 ) { index = 0; }
			while ( state.stack.length > index ) {
				var layer = state.stack.pop();
				if ( layer.raf ) { cancelAnimationFrame( layer.raf ); layer.raf = 0; }
				if ( layer.el ) { layer.el.remove(); }
			}
			if ( ! keepSource ) {
				state.source = null;
				state.pendingSource = null;
			}
			applyVisibility();
		}
		function closeAll( keepSource ) {
			clearTimer( 'pendingRoot' ); clearTimer( 'pendingChild' ); clearTimer( 'closeAllTimer' ); clearTimer( 'closeChildTimer' );
			removeFrom( 0, !! keepSource );
			state.source = keepSource ? state.source : null;
			state.pendingSource = null;
		}
		function backOne() {
			if ( state.stack.length <= 1 ) { closeAll( false ); return; }
			var layer = state.stack.pop();
			if ( layer ) {
				if ( layer.raf ) { cancelAnimationFrame( layer.raf ); }
				layer.el.remove();
			}
			applyVisibility();
			clearTimer( 'closeAllTimer' );
			clearTimer( 'closeChildTimer' );
		}
		function returnTo( index ) {
			if ( index < 0 || index >= state.stack.length ) { return; }
			removeFrom( index + 1 );
			clearTimer( 'closeAllTimer' );
			clearTimer( 'closeChildTimer' );
			applyVisibility();
		}

		function openRoot( info, sourceLink, anchor, locked ) {
			clearTimer( 'pendingRoot' ); clearTimer( 'pendingChild' ); clearTimer( 'closeAllTimer' ); clearTimer( 'closeChildTimer' );
			removeFrom( 0, true );
			state.source = sourceLink;
			state.pendingSource = null;
			createLayer( info.term, 0, anchor, sourceLink, !! locked );
		}
		function openTermAt( termId, depth, sourceLink, anchor, locked ) {
			var term = termIndex && termIndex.byId[ termId ];
			if ( ! term ) {
				fetchTerms().then( function ( idx ) {
					var t = idx.byId[ termId ];
					if ( t ) { openTermAt( termId, depth, sourceLink, anchor, locked ); }
				} ).catch( function () {} );
				return;
			}
			while ( state.stack.length > depth ) {
				var old = state.stack.pop();
				if ( old.raf ) { cancelAnimationFrame( old.raf ); }
				old.el.remove();
			}
			createLayer( term, depth, anchor, sourceLink, !! locked );
		}

		function scheduleRoot( sourceLink, info ) {
			clearTimer( 'pendingRoot' );
			state.pendingSource = sourceLink;
			state.pendingRoot = setTimeout( function () {
				state.pendingRoot = 0;
				if ( ! sourceLink.isConnected ) { return; }
				if ( state.stack.length ) { return; }
				openRoot( info, sourceLink, anchorPoint( sourceLink ), false );
			}, CFG.rootDelay );
		}

		function scheduleCloseAll() {
			if ( coarse ) { return; }
			clearTimer( 'closeAllTimer' );
			state.closeAllTimer = setTimeout( function () {
				state.closeAllTimer = 0;
				closeAll( false );
			}, CFG.grace );
		}
		function scheduleCloseChild( index ) {
			clearTimer( 'closeChildTimer' );
			state.closeChildIndex = index;
			state.closeChildTimer = setTimeout( function () {
				state.closeChildTimer = 0;
				if ( state.closeChildIndex >= 0 ) { removeFrom( state.closeChildIndex ); }
				state.closeChildIndex = -1;
			}, CFG.grace );
		}

		function layerAt( el ) {
			var card = closest( el, '.nv-lock' );
			if ( ! card ) { return null; }
			for ( var i = 0; i < state.stack.length; i++ ) {
				if ( state.stack[ i ].el === card ) { return state.stack[ i ]; }
			}
			return null;
		}

		/* ---- page term source: hover/click ---- */
		function onDocOver( e ) {
			var a = closest( e.target, 'a' );
			if ( e.target.closest( '.nv-lock' ) ) { return; }
			if ( !a || !isBody( a ) || isReference( a ) ) { return; }
			var info = termFromAnchor( a );
			if ( !info ) { return; }
			if ( a === state.source ) {
				clearTimer( 'closeAllTimer' );
				clearTimer( 'closeChildTimer' );
				return;
			}
			if ( coarse ) { return; }
			if ( state.stack.length ) { closeAll( false ); }
			scheduleRoot( a, info );
		}
		function onDocOut( e ) {
			var a = closest( e.target, 'a' );
			if ( !a ) { return; }
			if ( state.pendingSource === a && state.pendingRoot ) {
				clearTimer( 'pendingRoot' );
				state.pendingSource = null;
			}
			if ( state.source !== a || ! state.stack.length ) { return; }
			var to = e.relatedTarget;
			if ( to && a.contains( to ) ) { return; }
			var root = state.stack[ 0 ];
			if ( ! root ) { return; }
			if ( ! root.locked ) { closeAll( false ); return; }
			if ( to && to.closest( '.nv-lock' ) ) { return; }
			if ( to === state.source || ( state.source && state.source.contains( to ) ) ) { return; }
			scheduleCloseAll();
		}

		function onCardOver( layer, e ) {
			var link = closest( e.target, '.nv-lock__term-link' );
			var idx = state.stack.indexOf( layer );
			if ( idx < 0 ) { return; }
			if ( link ) {
				var id = link.getAttribute( 'data-term-id' );
				if ( ! id ) { return; }
				var existing = -1;
				state.stack.forEach( function ( l, i ) { if ( l.term.id === id ) { existing = i; } } );
				if ( existing >= 0 ) {
					clearTimer( 'pendingChild' );
					state.pendingChild = setTimeout( function () {
						state.pendingChild = 0;
						returnTo( existing );
					}, CFG.childDelay );
					return;
				}
				var currentChild = state.stack[ idx + 1 ];
				if ( currentChild && currentChild.sourceLink === link ) {
					clearTimer( 'closeChildTimer' );
					return;
				}
				if ( state.stack.length > idx + 1 ) { removeFrom( idx + 1 ); }
				clearTimer( 'pendingChild' );
				state.pendingChild = setTimeout( function () {
					state.pendingChild = 0;
					if ( ! link.isConnected ) { return; }
					openTermAt( id, idx + 1, link, anchorPoint( link ), false );
				}, CFG.childDelay );
				return;
			}
			// Pointer entered blank/title of an ancestor card: close that card's child branch.
			if ( state.stack.length > idx + 1 ) {
				removeFrom( idx + 1 );
			}
		}

		function onCardOut( layer, e ) {
			var link = closest( e.target, '.nv-lock__term-link' );
			if ( ! link ) { return; }
			var to = e.relatedTarget;
			if ( to && ( link.contains( to ) || closest( to, '.nv-lock__term-link' ) === link ) ) { return; }
			if ( state.pendingChild ) { clearTimer( 'pendingChild' ); }
			var idx = state.stack.indexOf( layer );
			if ( idx < 0 ) { return; }
			var child = state.stack[ idx + 1 ];
			if ( ! child || child.sourceLink !== link ) { return; }
			if ( ! child.locked ) {
				removeFrom( idx + 1 );
				return;
			}
			if ( to && child.el.contains( to ) ) { return; }
			if ( to && to.closest( '.nv-lock' ) ) {
				removeFrom( idx + 1 );
				return;
			}
			if ( to === state.source || ( state.source && state.source.contains( to ) ) ) {
				removeFrom( idx + 1 );
				return;
			}
			scheduleCloseChild( idx + 1 );
		}

		function onCardLeave( layer, e ) {
			var to = e.relatedTarget;
			if ( ! to ) { scheduleCloseAll(); return; }
			var targetLayer = layerAt( to );
			if ( targetLayer ) {
				if ( targetLayer === layer ) { return; }
				if ( targetLayer.depth > layer.depth ) { return; }
				if ( layer.depth === 0 ) { return; }
				if ( layer.sourceLink && ( layer.sourceLink === to || layer.sourceLink.contains( to ) ) ) { return; }
				// returning to an ancestor's blank area closes this branch, parent stays
				removeFrom( layer.depth );
				return;
			}
			if ( state.source && ( state.source === to || state.source.contains( to ) ) ) {
				if ( layer.depth === 0 ) { return; }
				removeFrom( layer.depth );
				return;
			}
			if ( layer.depth > 0 ) {
				scheduleCloseAll();
			} else {
				scheduleCloseAll();
			}
		}

		function onCardClick( layer, e ) {
			var back = closest( e.target, '.nv-lock__back' );
			if ( back ) { return; }
			var a = closest( e.target, 'a' );
			if ( ! a ) { return; }
			if ( closest( a, '.nv-lock__header' ) ) { return; }
			var id = a.getAttribute( 'data-term-id' );
			if ( ! id ) { return; }
			e.preventDefault();
			e.stopPropagation();
			var idx = state.stack.indexOf( layer );
			if ( idx < 0 ) { return; }
			var existing = -1;
			state.stack.forEach( function ( l, i ) { if ( l.term.id === id ) { existing = i; } } );
			if ( existing >= 0 ) { returnTo( existing ); return; }
			var anchor = ( coarse && ( e.clientX || e.clientY ) ) ? { x: e.clientX, y: e.clientY } : anchorPoint( a );
			openTermAt( id, idx + 1, a, anchor, true );
		}

		/* ---- mouse position, scroll/resize ---- */
		document.addEventListener( 'mousemove', function ( e ) {
			state.pointer.x = e.clientX;
			state.pointer.y = e.clientY;
		}, { passive: true } );
		window.addEventListener( 'scroll', function () {
			if ( state.stack.length ) { closeAll( false ); }
		}, { passive: true } );
		window.addEventListener( 'resize', function () {
			if ( state.stack.length ) { closeAll( false ); }
		} );

		/* ---- source hover ---- */
		window.addEventListener( 'mouseover', onDocOver, true );
		window.addEventListener( 'mouseout', onDocOut, true );

		/* ---- touch: one tap shows card, no hover wait ---- */
		var touchInfo = null;
		document.addEventListener( 'touchstart', function ( e ) {
			coarse = true;
			if ( e.touches && e.touches.length === 1 ) {
				touchInfo = { x: e.touches[ 0 ].clientX, y: e.touches[ 0 ].clientY, moved: false, target: e.target };
			}
		}, { capture: true, passive: true } );
		document.addEventListener( 'touchmove', function ( e ) {
			if ( ! touchInfo || ! e.touches || ! e.touches.length ) { return; }
			var dx = e.touches[ 0 ].clientX - touchInfo.x;
			var dy = e.touches[ 0 ].clientY - touchInfo.y;
			if ( dx * dx + dy * dy > 100 ) { touchInfo.moved = true; }
		}, { capture: true, passive: true } );
		document.addEventListener( 'touchend', function ( e ) {
			if ( ! touchInfo ) { return; }
			var a = closest( touchInfo.target, 'a' );
			var moved = touchInfo.moved;
			var tapPoint = { x: touchInfo.x, y: touchInfo.y };
			touchInfo = null;
			if ( ! coarse || moved || ! a || a.closest( '.nv-lock' ) ) { return; }
			if ( ! potentialTermAnchor( a ) ) { return; }
			e.preventDefault();
			e.stopPropagation();
			state.suppressClickUntil = Date.now() + 700;
			closeAll( false );
			var info = termFromAnchor( a );
			if ( info ) {
				openRoot( info, a, tapPoint, true );
			} else {
				fetchTerms().then( function () {
					var later = termFromAnchor( a );
					if ( later ) { openRoot( later, a, tapPoint, true ); }
				} ).catch( function () {} );
			}
		}, { capture: true, passive: false } );
		document.addEventListener( 'pointerdown', function ( e ) {
			if ( e.pointerType === 'touch' ) { coarse = true; }
		}, { capture: true, passive: true } );
		document.addEventListener( 'click', function ( e ) {
			if ( Date.now() < state.suppressClickUntil ) {
				e.preventDefault();
				e.stopPropagation();
				return;
			}
			if ( coarse ) {
				var a = closest( e.target, 'a' );
				if ( a && ! a.closest( '.nv-lock' ) ) {
					var info = termFromAnchor( a );
					if ( info ) {
						e.preventDefault();
						e.stopPropagation();
						openRoot( info, a, { x: e.clientX || pointFromLink( a ).x, y: e.clientY || pointFromLink( a ).y }, true );
						return;
					}
				}
			}
			if ( ! state.stack.length ) { return; }
			if ( closest( e.target, '.nv-lock' ) ) { return; }
			if ( state.source && ( e.target === state.source || state.source.contains( e.target ) ) ) {
				return;
			}
			closeAll( false );
		}, true );

		function onKeydown( e ) {
			if ( e.key === 'Escape' && state.stack.length ) {
				e.preventDefault();
				closeAll( false );
				return;
			}
			if ( e.key !== 'Enter' || e.ctrlKey || e.metaKey || e.altKey ) { return; }
			var a = closest( e.target, 'a' );
			if ( !a || a.closest( '.nv-lock' ) || !isBody( a ) || isReference( a ) ) { return; }
			var info = termFromAnchor( a );
			if ( !info ) { return; }
			e.preventDefault();
			closeAll( false );
			openRoot( info, a, pointFromLink( a ), true );
		}
		document.addEventListener( 'keydown', onKeydown, true );

		/* ---- boot ---- */
		fetchTerms().catch( function () {} );
		window.NvLock = {
			version: '2.0.0',
			isOpen: function () { return state.stack.length > 0; },
			close: function () { closeAll( false ); },
			status: function () {
				return {
					terms: state.stack.map( function ( l ) { return l.term.name; } ),
					locked: state.stack.map( function ( l ) { return !! l.locked; } ),
					progress: state.stack.map( function ( l ) { return l.progress; } ),
					bounds: state.stack.map( function ( l ) { return l.bounds; } ),
					anchors: state.stack.map( function ( l ) { return l.anchor; } ),
					single: state.single
				};
			}
		};
	}

	if ( window.mw && mw.loader && mw.loader.using ) {
		mw.loader.using( [ 'mediawiki.util' ] ).then( function () {
			if ( document.readyState === 'loading' ) { document.addEventListener( 'DOMContentLoaded', boot ); }
			else { boot(); }
		} );
	} else if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', boot );
	} else {
		boot();
	}
} )();

/* Accessible names for Citizen collapse buttons whose labels live in hidden icons. */
( function () {
	'use strict';
	function label() {
		document.querySelectorAll( '#citizen-toc .citizen-toc-toggle' ).forEach( function ( b ) {
			if ( b.getAttribute( 'aria-label' ) ) { return; }
			var t = ( b.textContent || '' ).replace( /\s+/g, ' ' ).trim();
			if ( t ) { b.setAttribute( 'aria-label', t ); }
		} );
		document.querySelectorAll( '.citizen-section-toggle' ).forEach( function ( b ) {
			if ( b.getAttribute( 'aria-label' ) ) { return; }
			var h = b.closest( '.citizen-section-heading' );
			if ( !h ) { return; }
			var clone = h.cloneNode( true );
			clone.querySelectorAll( 'button, .citizen-section-toggle, .mw-editsection' ).forEach( function ( x ) { x.remove(); } );
			var title = ( clone.textContent || '' ).replace( /\s+/g, ' ' ).trim();
			if ( title ) { b.setAttribute( 'aria-label', '折叠或展开「' + title + '」章节' ); }
		} );
	}
	function boot() { label(); setTimeout( label, 350 ); }
	if ( document.readyState === 'loading' ) { document.addEventListener( 'DOMContentLoaded', boot ); }
	else { boot(); }
} )();

/* 2026-10-25 shared layout behaviour:
   - move the existing parliament DOM into the country infobox (same data)
   - collapse the detailed legend inside the same component
   - point #议会席位 at the infobox component
   - reset only the newly shown table's local scrollLeft on tab switch
   No global wheel/touch interception. */
( function () {
	'use strict';

	function moveParliament() {
		var box = document.querySelector( '.mw-parser-output .nv-infobox' );
		var parliament = document.querySelector( '.mw-parser-output .nv-parliament' );
		if ( !box || !parliament || box.contains( parliament ) ) {
			return;
		}

		var host = document.createElement( 'div' );
		host.className = 'nv-infobox__parliament';
		host.id = '议会席位';

		var legend = parliament.querySelector( 'table.nv-parliament__legend' );
		if ( legend ) {
			var mini = legend.cloneNode( true );
			mini.classList.add( 'nv-parliament__mini' );
			Array.prototype.slice.call( mini.rows ).slice( 4 ).forEach( function ( row ) {
				row.remove();
			} );

			var details = document.createElement( 'details' );
			details.className = 'nv-parliament__legend-details';
			var summary = document.createElement( 'summary' );
			var groupCount = Math.max( 0, legend.rows.length - 1 );
			summary.textContent = '席位构成 · ' + groupCount + ' 组';
			details.appendChild( summary );

			legend.parentNode.removeChild( legend );
			details.appendChild( legend );

			parliament.appendChild( mini );
			parliament.appendChild( details );
		}

		host.appendChild( parliament );
		box.appendChild( host );

		var heading = Array.prototype.slice.call(
			document.querySelectorAll( '.mw-parser-output h2' )
		).find( function ( h ) {
			return h.textContent.trim() === '议会席位';
		} );
		if ( heading ) {
			var section = heading.closest( '.citizen-section' );
			if ( section ) {
				// TemplateStyles for party colors lives inside the section body.
				// Move it to head before hiding the now-empty source section.
				Array.prototype.forEach.call( section.querySelectorAll( 'style' ), function ( styleEl ) {
					document.head.appendChild( styleEl );
				} );
				Array.prototype.forEach.call( section.querySelectorAll( '[id="议会席位"]' ), function ( el ) {
					el.removeAttribute( 'id' );
				} );
				section.hidden = true;
			} else if ( heading ) {
				heading.remove();
			}
		}
	}

	function resetShownTableScroll( tab ) {
		var panelId = tab.getAttribute( 'aria-controls' );
		if ( !panelId ) {
			return;
		}
		setTimeout( function () {
			var panel = document.getElementById( panelId );
			if ( !panel || panel.hidden ) {
				return;
			}
			Array.prototype.forEach.call(
				panel.querySelectorAll( '.nv-table-scroll' ),
				function ( wrap ) {
					wrap.scrollLeft = 0;
				}
			);
		}, 0 );
	}

	function onTabClick( event ) {
		var tab = event.target.closest && event.target.closest( '.tabber__tab' );
		if ( tab ) {
			resetShownTableScroll( tab );
		}
	}

	function init() {
		moveParliament();
		document.addEventListener( 'click', onTabClick );
	}

	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', init, { once: true } );
	} else {
		init();
	}
}() );