跳到正文
Novark

MediaWiki:Common.js:修订间差异

Phase1EmergencyAdmin
Phase1EmergencyAdmin​(留言 | 贡献) (细节收尾:复制失败手动回退后恢复按钮原标签)
Phase1EmergencyAdmin
Phase1EmergencyAdmin​(留言 | 贡献) (AI辅助:删除页尾重复讨论行,保留原生顶部讨论入口)
小
 
(未显示2个用户的15个中间版本)
第1行: 第1行:
/* Novark v2 功能组件:经济计算器、法术筛选/排序。
/* Generated from site-scripts/common. Edit the source files, not this bundle. */
 
/* Source: page-tools.js */
/* Page tools: table-backed calculators and spell filters.
  * 自定义控件由本脚本创建;MediaWiki 正文不直接嵌入 input/select。
  * 自定义控件由本脚本创建;MediaWiki 正文不直接嵌入 input/select。
  * 数据/公式来自页面公开表格与旧站计算器的可视语义。 */
  * 数据/公式来自页面公开表格与旧站计算器的可视语义。 */
第47行: 第50行:
     return parts.length === 2 ? Number(parts[0]) / Number(parts[1]) : Number(parts[0]);
     return parts.length === 2 ? Number(parts[0]) / Number(parts[1]) : Number(parts[0]);
   }
   }
   function economyRows(id) {
   function economyRows(scope, id) {
     var table = document.getElementById(id);
     var table = scope.querySelector('#' + id);
     if (!table) return [];
     if (!table) return [];
     return Array.prototype.slice.call(table.rows).filter(function (row) {
     return Array.prototype.slice.call(table.rows).filter(function (row) {
第56行: 第59行:
     });
     });
   }
   }
   function readEconomyData() {
   function readEconomyData(scope) {
     return {
     return {
       alpha: economyRows('nv-economy-alpha').map(function (r) { return [r[0], { alpha: economyNumber(r[1]) }]; }),
       alpha: economyRows(scope, '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]) }]; }),
       beta: economyRows(scope, '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]) }]; }),
       gamma: economyRows(scope, 'nv-economy-gamma').map(function (r) { return [r[0], { gamma: economyNumber(r[1]) }]; }),
       currencies: economyRows('nv-economy-currencies').filter(function (r) {
       currencies: economyRows(scope, 'nv-economy-currencies').filter(function (r) {
         return economyNumber(r[1]) > 0 && economyNumber(r[2]) > 0;
         return economyNumber(r[1]) > 0 && economyNumber(r[2]) > 0;
       }).map(function (r) {
       }).map(function (r) {
第69行: 第72行:
   }
   }


   function buildPriceUI(data) {
   function bindControls(controls, update) {
     var host = document.getElementById('mien-price-calculator');
     controls.forEach(function (control) {
    if (!host || host.dataset.built === 'true') return;
      control.addEventListener(control.tagName === 'SELECT' ? 'change' : 'input', update);
    });
    update();
  }
 
  function buildPriceUI(host, data) {
     host.dataset.built = 'true';
     host.dataset.built = 'true';
     host.innerHTML = '<div class="mien-price-calculator-title">价格计算器</div><div class="mien-price-calculator-row"></div>' +
     host.innerHTML = '<div class="mien-price-calculator-title">价格计算器</div><div class="mien-price-calculator-row"></div>' +
第87行: 第95行:
     row.appendChild(label('技术', gamma));
     row.appendChild(label('技术', gamma));
     row.appendChild(label('货币', currency));
     row.appendChild(label('货币', currency));
    var result = host.querySelector('#mien-price-result');
    var limit = host.querySelector('#mien-price-limit');
    var formula = host.querySelector('#mien-price-formula');


     function update() {
     function update() {
第98行: 第109行:
       var finalPrice = gp * rate;
       var finalPrice = gp * rate;
       var currencyName = optionText(currency);
       var currencyName = optionText(currency);
       host.querySelector('#mien-price-result').textContent = formatNumber(finalPrice) + ' ' + currencyName + '(' + formatNumber(gp) + ' GP)';
       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');
       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'); }
       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'); }
       else { limit.textContent = '限额 ' + formatNumber(cap) + ' GP:需 DM 裁定'; limit.classList.add('mien-price-limit-over'); }
       host.querySelector('#mien-price-formula').textContent =
       formula.textContent =
         '实际价值:ω* = ω0 × α × β × γ = ' + formatNumber(baseValue) + ' GP × ' + a + ' × ' + b + ' × ' + g +
         '实际价值:ω* = ω0 × α × β × γ = ' + formatNumber(baseValue) + ' GP × ' + a + ' × ' + b + ' × ' + g +
         ' = ' + formatNumber(gp) + ' GP。结算价格:ω = ω* × δ* = ' + formatNumber(gp) + ' GP × ' + rate +
         ' = ' + formatNumber(gp) + ' GP。结算价格:ω = ω* × δ* = ' + formatNumber(gp) + ' GP × ' + rate +
         ' = ' + formatNumber(finalPrice) + ' ' + currencyName + '。';
         ' = ' + formatNumber(finalPrice) + ' ' + currencyName + '。';
     }
     }
     [base, alpha, beta, gamma, currency].forEach(function (c) {
     bindControls([base, alpha, beta, gamma, currency], update);
      c.addEventListener('input', update);
      c.addEventListener('change', update);
    });
    update();
   }
   }


   function buildCreditUI(data) {
   function buildCreditUI(host, data) {
    var host = document.getElementById('mien-credit-currency-calculator');
    if (!host || host.dataset.built === 'true') return;
     host.dataset.built = 'true';
     host.dataset.built = 'true';
     host.innerHTML = '<div class="mien-currency-calculator-title">汇率计算器</div><div class="mien-currency-calculator-row"></div>' +
     host.innerHTML = '<div class="mien-currency-calculator-title">汇率计算器</div><div class="mien-currency-calculator-row"></div>' +
第131行: 第135行:
     row.appendChild(label('目标货币', target));
     row.appendChild(label('目标货币', target));
     host.appendChild(el('p', null, '选项来自下方货币表;未标明汇率的独立本位币不参与换算。'));
     host.appendChild(el('p', null, '选项来自下方货币表;未标明汇率的独立本位币不参与换算。'));
    var result = host.querySelector('#mien-credit-result');
    var nominalResult = host.querySelector('#mien-credit-nominal-result');
    var marketResult = host.querySelector('#mien-credit-market-result');
    var formula = host.querySelector('#mien-credit-formula');


     function currencyName(selectItem) {
     function currencyName(selectItem) {
第144行: 第152行:
       var snGp = value / sn, smGp = value / sm;
       var snGp = value / sn, smGp = value / sm;
       var targetAmount = smGp * tn, targetMarket = smGp * tm;
       var targetAmount = smGp * tn, targetMarket = smGp * tm;
       host.querySelector('#mien-credit-result').textContent = formatNumber(targetAmount) + ' ' + currencyName(target);
       result.textContent = formatNumber(targetAmount) + ' ' + currencyName(target);
       host.querySelector('#mien-credit-nominal-result').textContent = formatNumber(snGp);
       nominalResult.textContent = formatNumber(snGp);
       host.querySelector('#mien-credit-market-result').textContent = formatNumber(smGp);
       marketResult.textContent = formatNumber(smGp);
       host.querySelector('#mien-credit-formula').textContent =
       formula.textContent =
         '源货币名义等值:' + formatNumber(value) + ' ' + currencyName(source) + ' ÷ ' + sn + ' = ' + formatNumber(snGp) + ' GP。' +
         '源货币名义等值:' + formatNumber(value) + ' ' + currencyName(source) + ' ÷ ' + sn + ' = ' + formatNumber(snGp) + ' GP。' +
         '源货币市场折算:' + formatNumber(value) + ' ' + currencyName(source) + ' ÷ ' + sm + ' = ' + formatNumber(smGp) + ' GP。' +
         '源货币市场折算:' + formatNumber(value) + ' ' + currencyName(source) + ' ÷ ' + sm + ' = ' + formatNumber(smGp) + ' GP。' +
第153行: 第161行:
         '市场参考:' + formatNumber(smGp) + ' GP × ' + tm + ' = ' + formatNumber(targetMarket) + ' ' + currencyName(target) + '。';
         '市场参考:' + formatNumber(smGp) + ' GP × ' + tm + ' = ' + formatNumber(targetMarket) + ' ' + currencyName(target) + '。';
     }
     }
     [amount, source, target].forEach(function (c) { c.addEventListener('input', update); c.addEventListener('change', update); });
     bindControls([amount, source, target], update);
    update();
   }
   }


   function spellNoValue(value) {
   function spellNoValue(value) {
     var v = String(value || '').trim();
     var text = String(value || '').trim();
     return (v === '' || v === '-' || v === '—' || v === '无') ? '无' : v;
     return !text || text === '-' || text === '—' || text === '无' ? '无' : text;
   }
   }
   function uniqueValues(values) {
 
     var seen = {};
  // Read each cell once. Filters retain row nodes, so native sorting can move them freely.
    return values.filter(function (v) {
   function readSpellRows(table) {
      if (!v || seen[v]) return false;
     return Array.from(table.rows).filter(function (row) {
      seen[v] = true;
      return row.cells.length && row.cells[0].tagName === 'TD';
       return true;
    }).map(function (row) {
      var cells = Array.from(row.cells, function (cell) { return cell.textContent.trim(); });
      return {
        element: row,
        searchText: cells.join(' ').toLowerCase(),
        className: spellNoValue(cells[3]),
        level: (cells[1] || '').replace(/\s*级$/, '').trim(),
        school: cells[2] || '',
        domain: spellNoValue(cells[4])
      };
    });
  }
 
  function spellSelect(id, labelText, values, optionLabel) {
    var select = el('select', { id: id, 'aria-label': labelText });
    select.appendChild(el('option', { value: '' }, '全部' + labelText));
    Array.from(new Set(values)).filter(Boolean).forEach(function (value) {
       select.appendChild(el('option', { value: value }, optionLabel ? optionLabel(value) : value));
     });
     });
    return select;
   }
   }
   function buildSpellUI() {
 
    var host = document.getElementById('spell-filter-host');
   function buildSpellUI(host, table) {
    var table = document.querySelector('.mien-spell-table');
    if (!host || !table || host.dataset.built === 'true') return;
     host.dataset.built = 'true';
     host.dataset.built = 'true';
     host.className = 'mien-spell-filter';
     host.classList.add('mien-spell-filter');
     var rows = spellRows(table);
     var rows = readSpellRows(table);
     var classes = uniqueValues(rows.reduce(function (values, row) {
     var classes = rows.reduce(function (values, row) {
      var value = spellNoValue(cellText(row, 3));
       return values.concat(row.className, row.className.split(/[\/、,,]/).map(function (value) { return value.trim(); }));
       return values.concat([value], value.split(/[\/、,,]/).map(function (v) { return v.trim(); }));
     }, []);
     }, []));
     var levels = rows.map(function (row) { return row.level; }).sort(function (a, b) { return Number(a) - Number(b); });
     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 search = el('input', { id: 'spell-search', type: 'search', placeholder: '搜索法术名称、简述、学派…', 'aria-label': '搜索法术' });
     var klass = el('select', { id: 'spell-class-filter', 'aria-label': '法表' });
     var classFilter = spellSelect('spell-class-filter', '法表', classes);
    [''].concat(classes).forEach(function (v) { klass.appendChild(el('option', { value: v }, v === '' ? '全部法表' : v)); });
     var levelFilter = spellSelect('spell-level-filter', '等级', levels, function (value) { return value + ' 级'; });
     var level = el('select', { id: 'spell-level-filter', 'aria-label': '等级' });
     var schoolFilter = spellSelect('spell-school-filter', '学派', rows.map(function (row) { return row.school; }));
    [''].concat(levels).forEach(function (v) { level.appendChild(el('option', { value: v }, v === '' ? '全部等级' : v + ' 级')); });
     var domainFilter = spellSelect('spell-domain-filter', '领域', rows.map(function (row) { return row.domain; }), function (value) { return value === '无' ? '无领域' : value; });
     var school = el('select', { id: 'spell-school-filter', 'aria-label': '学派' });
    var controls = [search, classFilter, levelFilter, schoolFilter, domainFilter];
    [''].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' }, '清除条件');
     var clear = el('button', { type: 'button', id: 'spell-clear' }, '清除条件');
     [search, klass, level, school, domain, clear].forEach(function (n) { host.appendChild(n); });
     controls.concat(clear).forEach(function (control) { host.appendChild(control); });
  }
 
    function applyFilters() {
      var query = search.value.trim().toLowerCase();
      rows.forEach(function (row) {
        var matches = (!query || row.searchText.indexOf(query) !== -1) &&
          (!classFilter.value || row.className.indexOf(classFilter.value) !== -1) &&
          (!levelFilter.value || row.level === levelFilter.value) &&
          (!schoolFilter.value || row.school === schoolFilter.value) &&
          (!domainFilter.value || row.domain === domainFilter.value);
        row.element.hidden = !matches;
        row.element.classList.toggle('mien-spell-row-hidden', !matches);
      });
    }


  function spellRows(table) {
     bindControls(controls, applyFilters);
     return Array.prototype.slice.call(table.querySelectorAll('tbody tr')).filter(function (row) { return row.cells && row.cells[0] && row.cells[0].tagName === 'TD'; });
     clear.addEventListener('click', function () {
  }
      controls.forEach(function (control) { control.value = ''; });
  function cellText(row, index) {
       applyFilters();
    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) {
    // MediaWiki owns sorting, keyboard access and direction indicators.
     var tbody = table.tBodies[0];
     rows.forEach(function (row) { row.element.cells[1].dataset.sortValue = row.level; });
    if (!tbody) return;
     table.classList.add('sortable');
    var headRow = (table.tHead && table.tHead.rows[0]) || table.rows[0];
     mw.loader.using('jquery.tablesorter').then(function () {
    var header = headRow ? headRow.cells[headerIndex] : null;
       if (table.isConnected) { $(table).tablesorter(); }
    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() {
   function initPageTools(scope) {
     if (document.getElementById('mien-price-calculator') || document.getElementById('mien-credit-currency-calculator')) {
     var price = scope.querySelector('#mien-price-calculator:not([data-built="true"])');
       var economy = readEconomyData();
    var credit = scope.querySelector('#mien-credit-currency-calculator:not([data-built="true"])');
    if (price || credit) {
       var economy = readEconomyData(scope);
       if (economy.alpha.length && economy.beta.length && economy.gamma.length && economy.currencies.length) {
       if (economy.alpha.length && economy.beta.length && economy.gamma.length && economy.currencies.length) {
         buildPriceUI(economy);
         if (price) { buildPriceUI(price, economy); }
         buildCreditUI(economy);
         if (credit) { buildCreditUI(credit, economy); }
       } else {
       } else {
         ['mien-price-calculator', 'mien-credit-currency-calculator'].forEach(function (id) {
         [price, credit].filter(Boolean).forEach(function (host) {
           var host = document.getElementById(id);
           host.textContent = '计算器需要本页完整的物价系数表和货币汇率表。';
          if (host) host.textContent = '计算器需要本页完整的物价系数表和货币汇率表。';
         });
         });
       }
       }
     }
     }
     buildSpellUI();
     var spellHost = scope.querySelector('#spell-filter-host:not([data-built="true"])');
     bindSpellTable();
    var spellTable = spellHost && scope.querySelector('.mien-spell-table');
     if (spellHost && spellTable) { buildSpellUI(spellHost, spellTable); }
   }
   }
   if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
 
  else init();
   // The hook remembers the initial content and also receives newly rendered fragments.
   if (window.mw && mw.hook) mw.hook('wikipage.content').add(init);
   mw.hook('wikipage.content').add(function ($content) {
    $content.each(function () { initPageTools(this); });
  });
}());
}());


/* ==========================================================================
/* Source: clipboard.js */
  弥恩 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();
}
}() );
 
/* Shared clipboard action for the page footer and glossary editor. */
/* Shared clipboard action for the page footer and glossary editor. */
window.nvCopyText = function (value, button) {
window.nvCopyText = function (value, button) {
第563行: 第304行:
};
};


/* Source: term-catalog.js */
/* Shared cached loader for the term JSON index (read-only consumers: NvLock preview
/* Shared cached loader for the term JSON index (read-only consumers: NvLock preview
   and the unified page footer). The editor keeps its own uncached fetch to read the
   and the unified page footer). The editor keeps its own uncached fetch to read the
第587行: 第329行:
}() );
}() );


/* Page-backed terms. Native pages/categories/redirects are the catalogue; the
  existing JSON supplies compatible IDs, explicit aliases and section entries. */
window.nvTermCatalog = ( function () {
'use strict';
var cached, loading, loadedAt = 0;
var excluded = new Set( [ '索引页面', '站点导航', '帮助与指南' ] );
var maintenance = new Set( [ '术语', '资料', '已锚定', '需要改进', '待改进', '剧透' ] );
function norm( value ) { return String( value || '' ).replace( /_/g, ' ' ).trim().toLowerCase(); }
function readPages( force ) {
var pages = new Map(), api = new mw.Api();
function read( continuation ) {
return api.get( Object.assign( {
action: 'query', formatversion: 2, generator: 'allpages', gapnamespace: 0,
// Native browser caching also covers navigation between articles.
maxage: force ? 0 : 60,
gapfilterredir: 'nonredirects', gaplimit: 'max',
prop: 'info|categories|redirects|pageprops', inprop: 'url',
cllimit: 'max', rdlimit: 'max', rdnamespace: 0, rdprop: 'title|fragment',
ppprop: 'disambiguation'
}, continuation || {} ) ).then( function ( result ) {
( result.query && result.query.pages || [] ).forEach( function ( page ) {
var old = pages.get( page.pageid );
if ( old ) {
page.categories = ( old.categories || [] ).concat( page.categories || [] );
page.redirects = ( old.redirects || [] ).concat( page.redirects || [] );
}
pages.set( page.pageid, page );
} );
return result.continue ? read( result.continue ) : Array.from( pages.values() );
} );
}
return read();
}
function combine( pages, metadata ) {
var terms = [], targets = Object.create( null ), order = ( metadata.categoryOrder || [] ).slice();
pages.forEach( function ( page ) {
var categories = Array.from( new Set( ( page.categories || [] ).map( function ( cat ) {
return cat.title.replace( /^(Category|分类):/, '' );
} ) ) );
if ( page.missing || page.ns !== 0 || !page.length || page.pageprops &&
Object.prototype.hasOwnProperty.call( page.pageprops, 'disambiguation' ) ||
categories.some( function ( cat ) { return excluded.has( cat ); } ) ||
[ '首页', '术语库', '术语库/编辑', '作者入口' ].indexOf( page.title ) >= 0 ) { return; }
var term = {
id: 'page-' + page.pageid, pageid: page.pageid, revid: page.lastrevid,
name: page.title, article: page.title, aliases: [], legacyIds: [],
categories: categories.filter( function ( cat ) { return !maintenance.has( cat ) && !/^使用.*的页面$/.test( cat ); } )
};
( page.redirects || [] ).forEach( function ( redirect ) {
if ( !redirect.fragment ) { term.aliases.push( redirect.title ); }
} );
terms.push( term );
[ page.title ].concat( term.aliases ).forEach( function ( title ) { targets[ norm( title ) ] = term; } );
} );
( metadata.terms || [] ).forEach( function ( record ) {
var page = targets[ norm( record.article || record.name ) ];
if ( !page ) { return; }
var term = page;
if ( record.section ) {
term = Object.assign( {}, record, { pageid: page.pageid, article: page.article, categories: record.categories || [], legacyIds: [], curated: true } );
terms.push( term );
} else {
if ( !term.curated ) { term.id = record.id; }
term.curated = true;
}
term.legacyIds.push( record.id );
term.categories = Array.from( new Set( term.categories.concat( record.categories || [] ) ) );
term.aliases = Array.from( new Set( ( term.aliases || [] ).concat( record.aliases || [], record.name || [] ) ) )
.filter( function ( alias ) { return norm( alias ) !== norm( term.name ); } );
} );
terms.forEach( function ( term ) {
term.categories.forEach( function ( category ) { if ( order.indexOf( category ) < 0 ) { order.push( category ); } } );
} );
return { terms: terms, categoryOrder: order, automatic: true };
}
return function ( force ) {
if ( !force && cached && Date.now() - loadedAt < 60000 ) { return Promise.resolve( cached ); }
if ( loading ) { return loading; }
loading = mw.loader.using( [ 'mediawiki.api', 'mediawiki.util' ] ).then( function () {
return Promise.all( [ readPages( force ), window.nvTermData().catch( function () { return { terms: [] }; } ) ] );
} )
.then( function ( values ) { cached = combine( values[ 0 ], values[ 1 ] ); loadedAt = Date.now(); loading = null; return cached; },
function ( error ) { loading = null; throw error; } );
return loading;
};
}() );
/* Source: term-preview.js */
/* ==========================================================================
/* ==========================================================================
   nv-lock.js · 渐进锁定阅读链(B 路线:卡片内容为规范词条正文)
   Term preview: progressive reading chains backed by canonical page content.
   - 真实 800ms 进度;满圈才 locked,可移入
   - 真实 800ms 进度;满圈才 locked,可移入
   - 根词 180ms 延迟;未满圈离开立即取消
   - 根词 180ms 延迟;未满圈离开立即取消
第596行: 第426行:
( function () {
( function () {
'use strict';
'use strict';
// Previews belong to reading pages, not navigation or revision tools.
if ( mw.config.get( 'wgIsMainPage' ) || mw.config.get( 'wgAction' ) !== 'view' ||
mw.config.get( 'wgDiffNewId' ) !== null || mw.config.get( 'wgNamespaceNumber' ) < 0 ) { return; }


function boot() {
function boot() {
if ( window.NvLock ) { return; }
if ( window.NvLock || !document.querySelector( '#mw-content-text .mw-parser-output' ) ) { return; }


var CFG = {
var CFG = {
第612行: 第445行:
var reduceMotion = window.matchMedia && window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches;
var reduceMotion = window.matchMedia && window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches;
var coarse = window.matchMedia && window.matchMedia( '(hover: none), (pointer: coarse)' ).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 termIndex = null;
var termLoading = null;
var termLoading = null;
第627行: 第457行:
closeChildTimer: 0,
closeChildTimer: 0,
closeChildIndex: -1,
closeChildIndex: -1,
suppressClick: null,
single: false
single: false
};
};
第643行: 第472行:
}
}
function isNavigationLink( a ) {
function isNavigationLink( a ) {
return !! closest( a, '.nv-chapter-nav, .nv-home-grid, .nv-home-world, .nv-home-masthead, .nv-card, .toc, .catlinks, .printfooter' );
return !! closest( a, '.nv-chapter-nav, .nv-home, .nv-card, .toc, .catlinks, .printfooter' );
}
}


第678行: 第507行:
if ( termIndex ) { return Promise.resolve( termIndex ); }
if ( termIndex ) { return Promise.resolve( termIndex ); }
if ( termLoading ) { return termLoading; }
if ( termLoading ) { return termLoading; }
termLoading = window.nvTermData().then( function ( data ) {
termLoading = window.nvTermCatalog().then( function ( data ) {
var byId = Object.create( null );
var byId = Object.create( null );
var byTitle = Object.create( null );
var byTitle = Object.create( null );
第686行: 第515行:
( data.terms || [] ).forEach( function ( t ) {
( data.terms || [] ).forEach( function ( t ) {
byId[ t.id ] = t;
byId[ t.id ] = t;
( t.legacyIds || [] ).forEach( function ( id ) { byId[ id ] = t; } );
if ( t.article && ! t.section ) { byArticle[ norm( t.article ) ] = t; }
if ( t.article && ! t.section ) { byArticle[ norm( t.article ) ] = t; }
if ( t.section ) { bySection[ norm( t.article || t.name ) + '#' + norm( t.section ) ] = t; }
if ( t.section ) { bySection[ norm( t.article || t.name ) + '#' + norm( t.section ) ] = t; }
第691行: 第521行:
var key = norm( n );
var key = norm( n );
if ( !key ) { return; }
if ( !key ) { return; }
byTitle[ key ] = t;
if ( Object.prototype.hasOwnProperty.call( byTitle, key ) && ( !byTitle[ key ] || byTitle[ key ].id !== t.id ) ) { byTitle[ key ] = null; }
if ( unique[ key ] && unique[ key ].id !== t.id ) { unique[ key ] = null; }
else { byTitle[ key ] = t; }
else { unique[ key ] = t; }
if ( t.curated ) {
if ( Object.prototype.hasOwnProperty.call( unique, key ) && ( !unique[ key ] || unique[ key ].id !== t.id ) ) { unique[ key ] = null; }
else { unique[ key ] = t; }
}
} );
} );
} );
} );
termIndex = { byId: byId, byTitle: byTitle, byArticle: byArticle, bySection: bySection, unique: unique, raw: data };
// Longest match first, grouped once by initial character. Ambiguous names stay excluded.
var matchesByInitial = Object.create( null );
Object.keys( unique ).filter( function ( key ) { return !! unique[ key ]; } )
.sort( function ( a, b ) { return b.length - a.length; } )
.forEach( function ( key ) {
var initial = key.charAt( 0 );
if ( !matchesByInitial[ initial ] ) { matchesByInitial[ initial ] = []; }
matchesByInitial[ initial ].push( { key: key, term: unique[ key ] } );
} );
termIndex = { byId: byId, byTitle: byTitle, byArticle: byArticle, bySection: bySection, matchesByInitial: matchesByInitial, raw: data };
return termIndex;
return termIndex;
} ).catch( function ( err ) {
} ).catch( function ( err ) {
第706行: 第548行:
}
}


/* ---- B 路线:悬浮卡内容来源改为规范词条正文 --------------------------------
/* Preview the canonical page or requested section in full.
  旧行为:卡片只显示 JSON 短定义。
  Parsed content keeps its own styles and extension modules. */
  新行为:拉取规范词条页解析后的正文,在同一个有界卡内完整阅读;排除页头工具、
  页尾维护元数据与旧术语卡,不嵌整站壳。圆环/锁定/关闭/嵌套手感保持原样。 */
var articleCache = Object.create( null );
var articleCache = Object.create( null );
var articleLoading = Object.create( null );
var articleLoading = Object.create( null );
var previewSequence = 0;
// Full articles can contain the same section/tab IDs as the host page or another card.
function scopePreview( article, body, title, section ) {
var prefix = 'nv-preview-' + ( ++previewSequence ) + '-';
var ids = new Map();
article.querySelectorAll( '[id]' ).forEach( function ( element ) {
ids.set( element.id, prefix + element.id ); element.id = prefix + element.id;
} );
article.querySelectorAll( '[aria-controls],[aria-labelledby],[aria-describedby],[for]' ).forEach( function ( element ) {
[ 'aria-controls', 'aria-labelledby', 'aria-describedby', 'for' ].forEach( function ( attr ) {
if ( element.hasAttribute( attr ) ) {
element.setAttribute( attr, element.getAttribute( attr ).split( /\s+/ ).map( function ( id ) { return ids.get( id ) || id; } ).join( ' ' ) );
}
} );
} );
article.querySelectorAll( 'a[href]' ).forEach( function ( link ) {
var raw = link.getAttribute( 'href' ), target = targetOf( link );
var fragment = raw.charAt( 0 ) === '#' ? mw.util.percentDecodeFragment( raw.slice( 1 ) ) :
( target && norm( target.title ) === norm( title ) ? target.hash : '' );
if ( ids.has( fragment ) ) { link.setAttribute( 'href', '#' + ids.get( fragment ) ); }
} );
var pending = null;
function scrollTarget() {
if ( !pending ) { return; }
body.scrollTop += pending.getBoundingClientRect().top - body.getBoundingClientRect().top;
pending = null;
}
function jump( target ) {
pending = target;
var panel = target.closest( '.tabber__panel' );
var tab = panel && article.querySelector( '[aria-controls="' + CSS.escape( panel.id ) + '"]' );
if ( tab && tab.getAttribute( 'aria-selected' ) !== 'true' ) { tab.click(); }
else { scrollTarget(); }
}
article.addEventListener( 'tabber:tabchange', function ( event ) {
// The extension owns switching; a card must not rewrite the host page's fragment.
event.stopPropagation();
if ( pending ) { requestAnimationFrame( scrollTarget ); }
if ( event.detail.source === 'init' && ids.has( section ) ) {
var target = article.querySelector( '#' + CSS.escape( ids.get( section ) ) );
section = '';
queueMicrotask( function () { jump( target ); } );
}
} );
article.addEventListener( 'click', function ( event ) {
var link = event.target.closest( 'a[href^="#' + prefix + '"]' );
if ( !link || link.classList.contains( 'tabber__tab' ) || event.ctrlKey || event.metaKey || event.shiftKey ) { return; }
var target = article.querySelector( '#' + CSS.escape( mw.util.percentDecodeFragment( link.hash.slice( 1 ) ) ) );
if ( target ) { event.preventDefault(); jump( target ); }
} );
}


function articleTitleOf( term ) {
function articleTitleOf( term ) {
第756行: 第648行:
} );
} );
} );
} );
// 大表包一层横向滚动容器,不撑出卡;图片按卡宽缩放。
// 复用原生资料表容器;只有裸表才补一层,避免卡内双重横滚。
clone.querySelectorAll( 'table' ).forEach( function ( table ) {
clone.querySelectorAll( 'table' ).forEach( function ( table ) {
if ( table.closest( '.nv-lock__table' ) ) { return; }
if ( table.closest( '.nv-lock__table' ) ) { return; }
var existing = table.parentElement;
if ( existing.classList.contains( 'nv-table-scroll' ) ) {
existing.classList.add( 'nv-lock__table' );
return;
}
var wrap = document.createElement( 'div' );
var wrap = document.createElement( 'div' );
wrap.className = 'nv-lock__table';
wrap.className = 'nv-lock__table';
第788行: 第685行:
return norm( sec.anchor ) === wanted || norm( sec.line ) === wanted;
return norm( sec.anchor ) === wanted || norm( sec.line ) === wanted;
} )[ 0 ];
} )[ 0 ];
if ( ! found ) { throw new Error( 'section-not-found' ); }
return new mw.Api().get( {
return new mw.Api().get( {
action: 'parse', formatversion: 2, page: title, section: found.index,
action: 'parse', formatversion: 2, page: title, section: found ? found.index : undefined,
prop: 'text|revid|modules|modulestyles',
prop: 'text|revid|modules|modulestyles',
disableeditsection: 1, disablelimitreport: 1, redirects: 1
disableeditsection: 1, disablelimitreport: 1, redirects: 1
第807行: 第703行:
var doc = new DOMParser().parseFromString( '<div>' + text + '</div>', 'text/html' );
var doc = new DOMParser().parseFromString( '<div>' + text + '</div>', 'text/html' );
var root = doc.querySelector( '.mw-parser-output' ) || doc.body;
var root = doc.querySelector( '.mw-parser-output' ) || doc.body;
var content = sanitizeArticle( root );
var preview = sanitizeArticle( root );
var modules = []
var modules = []
.concat( ( res.parse.modules || [] ) )
.concat( ( res.parse.modules || [] ) )
第815行: 第711行:
if ( ! root.contains( style ) ) { externalStyles.push( style.textContent || '' ); }
if ( ! root.contains( style ) ) { externalStyles.push( style.textContent || '' ); }
} );
} );
articleCache[ cacheKey ] = { content: content, modules: modules, styles: externalStyles };
articleCache[ cacheKey ] = { content: preview, title: res.parse.title, revid: res.parse.revid, modules: modules, styles: externalStyles };
delete articleLoading[ cacheKey ];
delete articleLoading[ cacheKey ];
return articleCache[ cacheKey ];
return articleCache[ cacheKey ];
第840行: 第736行:
// 只处理段落/列表等正文文本节点;已在链接、表格、标题、脚注里的文字不重复加链。
// 只处理段落/列表等正文文本节点;已在链接、表格、标题、脚注里的文字不重复加链。
function linkifyTerms( scope, currentId ) {
function linkifyTerms( scope, currentId ) {
if ( ! termIndex || ! termIndex.unique ) { return; }
if ( ! termIndex ) { return; }
var keys = Object.keys( termIndex.unique ).filter( function ( key ) {
return !! termIndex.unique[ key ] && termIndex.unique[ key ].id !== currentId;
} ).sort( function ( a, b ) { return b.length - a.length; } );
if ( ! keys.length ) { return; }
var walker = document.createTreeWalker( scope, NodeFilter.SHOW_TEXT, {
var walker = document.createTreeWalker( scope, NodeFilter.SHOW_TEXT, {
acceptNode: function ( node ) {
acceptNode: function ( node ) {
第860行: 第752行:
var text = node.nodeValue;
var text = node.nodeValue;
var lower = text.toLowerCase();
var lower = text.toLowerCase();
var fragment = document.createDocumentFragment();
var fragment = null;
var i = 0, buffer = '';
var i = 0, textStart = 0;
while ( i < text.length ) {
while ( i < text.length ) {
var hit = null, hitKey = '';
var hit = null, hitKey = '';
for ( var k = 0; k < keys.length; k++ ) {
var candidates = termIndex.matchesByInitial[ lower.charAt( i ) ] || [];
var key = keys[ k ];
for ( var k = 0; k < candidates.length; k++ ) {
if ( key.length > hitKey.length && lower.substr( i, key.length ) === key ) {
var candidate = candidates[ k ];
hit = termIndex.unique[ key ];
if ( candidate.term.id !== currentId && lower.startsWith( candidate.key, i ) ) {
hitKey = key;
hit = candidate.term;
hitKey = candidate.key;
break;
}
}
}
}
if ( hit ) {
if ( hit ) {
if ( buffer ) { fragment.appendChild( document.createTextNode( buffer ) ); buffer = ''; }
if ( !fragment ) { fragment = document.createDocumentFragment(); }
if ( i > textStart ) { fragment.appendChild( document.createTextNode( text.slice( textStart, i ) ) ); }
var link = document.createElement( 'a' );
var link = document.createElement( 'a' );
link.className = 'nv-lock__term-link';
link.className = 'nv-lock__term-link';
第881行: 第776行:
fragment.appendChild( link );
fragment.appendChild( link );
i += hitKey.length;
i += hitKey.length;
textStart = i;
} else {
} else {
buffer += text.charAt( i++ );
i++;
}
}
}
}
if ( buffer ) { fragment.appendChild( document.createTextNode( buffer ) ); }
if ( fragment ) {
node.parentNode.replaceChild( fragment, node );
if ( textStart < text.length ) { fragment.appendChild( document.createTextNode( text.slice( textStart ) ) ); }
node.parentNode.replaceChild( fragment, node );
}
} );
} );
}
}
第895行: 第793行:
var title = articleTitleOf( layer.term );
var title = articleTitleOf( layer.term );
var section = layer.term.section || '';
var section = layer.term.section || '';
var cacheKey = section ? title + '\x1f' + section : title;
function insert( entry ) {
function insert( entry ) {
if ( ! layer.el || ! layer.el.isConnected ) { return; }
if ( ! layer.el || ! layer.el.isConnected ) { return; }
第905行: 第802行:
article.setAttribute( 'lang', 'zh-Hans' );
article.setAttribute( 'lang', 'zh-Hans' );
article.setAttribute( 'dir', 'ltr' );
article.setAttribute( 'dir', 'ltr' );
article.setAttribute( 'data-preview-mode', 'full' );
( entry && entry.styles ? entry.styles : [] ).forEach( function ( css ) {
( entry && entry.styles ? entry.styles : [] ).forEach( function ( css ) {
var style = document.createElement( 'style' );
var style = document.createElement( 'style' );
第912行: 第810行:
article.appendChild( content.cloneNode( true ) );
article.appendChild( content.cloneNode( true ) );
body.appendChild( article );
body.appendChild( article );
scopePreview( article, body, entry.title || title, section );
annotateTermLinks( article, layer.term.id );
annotateTermLinks( article, layer.term.id );
linkifyTerms( article, layer.term.id );
linkifyTerms( article, layer.term.id );
第927行: 第826行:
}
}
}
}
function render( entry ) {
fetchArticle( title, section ).then( insert, function () {
if ( ! layer.el || ! layer.el.isConnected ) { return; }
insert( entry );
}
if ( articleCache[ cacheKey ] ) { render( articleCache[ cacheKey ] ); return; }
fetchArticle( title, section ).then( render, function () {
if ( ! layer.el || ! layer.el.isConnected ) { return; }
if ( ! layer.el || ! layer.el.isConnected ) { return; }
body.replaceChildren();
body.replaceChildren();
第964行: 第858行:
if ( ! term ) { return null; }
if ( ! term ) { return null; }
} else if ( target.hash ) {
} else if ( target.hash ) {
// Only an explicitly registered section term may preview a page#section link.
var pageTerm = termIndex.byArticle[ norm( target.title ) ] || termIndex.byTitle[ norm( target.title ) ];
term = termIndex.bySection[ norm( target.title ) + '#' + norm( target.hash ) ] || null;
term = termIndex.bySection[ norm( pageTerm ? pageTerm.article : target.title ) + '#' + norm( target.hash ) ] || null;
if ( ! term ) { return null; }
if ( !term && pageTerm && !pageTerm.section ) {
term = Object.assign( {}, pageTerm, { id: pageTerm.id + '#' + target.hash, section: target.hash, name: pageTerm.name + ' · ' + target.hash } );
}
if ( !term ) { return null; }
} else {
} else {
term = termIndex.byTitle[ norm( target.title ) ] || termIndex.byArticle[ norm( target.title ) ] || null;
term = termIndex.byArticle[ norm( target.title ) ] || termIndex.byTitle[ norm( target.title ) ] || null;
if ( ! term || term.section ) { return null; }
if ( ! term || term.section ) { return null; }
}
}
第983行: 第880行:
}
}


function potentialTermAnchor( a ) {
if ( ! a || ! isBody( a ) || isReference( a ) || a.closest( '.nv-lock' ) ) { return false; }
return !! infoForTarget( a, null, false );
}
function pointFromLink( a ) {
function pointFromLink( a ) {
var r = a.getBoundingClientRect();
var r = a.getBoundingClientRect();
第1,031行: 第924行:
card.addEventListener( 'mouseover', function ( e ) { onCardOver( layer, e ); } );
card.addEventListener( 'mouseover', function ( e ) { onCardOver( layer, e ); } );
card.addEventListener( 'mouseout', function ( e ) { onCardOut( 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.el = card;
layer.ring = card.querySelector( '.nv-lock__ring-arc' );
layer.ring = card.querySelector( '.nv-lock__ring-arc' );
第1,383行: 第1,274行:
return;
return;
}
}
if ( layer.depth > 0 ) {
scheduleCloseAll();
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 info = infoForTarget( a, layer.term.id, true );
if ( ! info ) { 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 === info.id ) { existing = i; } } );
if ( existing >= 0 ) { returnTo( existing ); return; }
var anchor = ( coarse && ( e.clientX || e.clientY ) ) ? { x: e.clientX, y: e.clientY } : anchorPoint( a );
openInfoAt( info, idx + 1, a, anchor, true );
}
/* ---- mouse position, scroll/resize ---- */
/* ---- mouse position, scroll/resize ---- */
document.addEventListener( 'mousemove', function ( e ) {
document.addEventListener( 'mousemove', function ( e ) {
第1,421行: 第1,290行:
window.addEventListener( 'mouseout', onDocOut, true );
window.addEventListener( 'mouseout', onDocOut, true );


/* ---- touch: one tap shows card, no hover wait ---- */
/* Article links always navigate. Touch preview has its own button. */
var touchInfo = null;
        function previewButtons(scope) {
document.addEventListener( 'touchstart', function ( e ) {
            scope.querySelectorAll('a[href]').forEach(function (a) {
coarse = true;
                if (a.nvPreviewButton || !isBody(a) || isReference(a)) { return; }
if ( e.touches && e.touches.length === 1 ) {
                var info = infoForTarget(a, null, !!a.closest('.nv-lock'));
touchInfo = { x: e.touches[ 0 ].clientX, y: e.touches[ 0 ].clientY, moved: false, target: e.target };
                if (!info) { return; }
}
                var button = document.createElement('button');
}, { capture: true, passive: true } );
                button.type = 'button'; button.className = 'nv-term-preview-trigger';
document.addEventListener( 'touchmove', function ( e ) {
                button.textContent = '◉'; button.title = '预览';
if ( ! touchInfo || ! e.touches || ! e.touches.length ) { return; }
                button.setAttribute('aria-label', '预览「' + (a.textContent || info.term.name).trim() + '」');
var dx = e.touches[ 0 ].clientX - touchInfo.x;
                button.nvTermAnchor = a; a.nvPreviewButton = button;
var dy = e.touches[ 0 ].clientY - touchInfo.y;
                a.insertAdjacentElement('afterend', button);
if ( dx * dx + dy * dy > 100 ) { touchInfo.moved = true; }
            });
}, { capture: true, passive: true } );
        }
document.addEventListener( 'touchend', function ( e ) {
        document.addEventListener('pointerdown', function (e) {
if ( ! touchInfo ) { return; }
            if (e.pointerType === 'touch') { coarse = true; }
var target = touchInfo.target;
        }, { capture: true, passive: true });
var a = closest( target, 'a' );
        document.addEventListener('click', function (e) {
var moved = touchInfo.moved;
            var button = closest(e.target, '.nv-term-preview-trigger');
var tapPoint = { x: touchInfo.x, y: touchInfo.y };
            if (button && button.nvTermAnchor) {
touchInfo = null;
                var a = button.nvTermAnchor;
if ( ! coarse || moved ) { return; }
                var parent = closest(a, '.nv-lock');
// A tap outside the panel closes it, including when it lands on a
                var layer = parent && state.stack.filter(function (item) { return item.el === parent; })[0];
// navigation link (native click then proceeds, unless a previewable
                var info = infoForTarget(a, layer && layer.term.id, !!parent);
// article link re-opens the panel below).
                if (!info) { return; }
if ( state.stack.length && ! closest( target, '.nv-lock' ) ) {
                e.preventDefault(); e.stopPropagation();
closeAll( false );
                if (layer) {
if ( ! a ) { return; }
                    var existing = state.stack.findIndex(function (item) { return item.term.id === info.id; });
}
                    if (existing >= 0) { returnTo(existing); }
if ( ! a || a.closest( '.nv-lock' ) ) { return; }
                    else { openInfoAt(info, state.stack.indexOf(layer) + 1, a, pointFromLink(a), true); }
if ( ! potentialTermAnchor( a ) ) {
                } else { openRoot(info, a, pointFromLink(a), true); }
if ( state.stack.length ) { closeAll( false ); }
                return;
return;
            }
}
            if (state.stack.length && !closest(e.target, '.nv-lock')) { closeAll(false); }
e.preventDefault();
        }, true);
e.stopPropagation();
        document.addEventListener('focusin', function (e) {
state.suppressClick = { link: a, until: Date.now() + 700 };
            if (coarse) { return; }
closeAll( false );
            var a = closest(e.target, 'a');
var info = termFromAnchor( a );
            var info = a && termFromAnchor(a);
if ( info ) {
            if (info) { openRoot(info, a, pointFromLink(a), true); }
openRoot( info, a, tapPoint, true );
        });
} else {
        mw.hook('wikipage.content').add(function (content) {
fetchTerms().then( function () {
            var scope = content && content.jquery ? content[0] : content;
var later = termFromAnchor( a );
            if (scope && scope.querySelectorAll && termIndex) { previewButtons(scope); }
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 ) {
// Touch open consumed the follow-up click: suppress it once, only for
// the link that triggered the card, then clear the marker. Other links
// and controls keep their native click during the same window.
var suppressed = state.suppressClick;
if ( suppressed ) {
if ( Date.now() < suppressed.until && closest( e.target, 'a' ) === suppressed.link ) {
state.suppressClick = null;
e.preventDefault();
e.stopPropagation();
return;
}
if ( Date.now() >= suppressed.until ) {
state.suppressClick = null;
}
}
if ( coarse ) {
var a = closest( e.target, 'a' );
if ( a && ! a.closest( '.nv-lock' ) && isBody( a ) && ! isReference( a ) ) {
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 ) {
function onKeydown( e ) {
第1,517行: 第1,345行:


/* ---- boot ---- */
/* ---- boot ---- */
fetchTerms().catch( function () {} );
fetchTerms().then( function () { previewButtons( document ); } ).catch( function () {} );
window.NvLock = {
window.NvLock = {
version: '2.2.0-preview',
version: '2.3.0-page-terms',
termCount: function () { return termIndex ? termIndex.raw.terms.length : -1; },
termCount: function () { return termIndex ? termIndex.raw.terms.length : -1; },
debugLink: function ( el ) { return { body: isBody( el ), target: targetOf( el ), ref: isReference( el ), nav: isNavigationLink( el ), info: infoForTarget( el, null, false ) }; },
debugLink: function ( el ) { return { body: isBody( el ), target: targetOf( el ), ref: isReference( el ), nav: isNavigationLink( el ), info: infoForTarget( el, null, false ) }; },
第1,550行: 第1,378行:
} )();
} )();


/* Accessible names for Citizen collapse buttons whose labels live in hidden icons. */
/* Source: table-layout.js */
( function () {
/* Shared table behaviour: wrap long description columns without intercepting input. */
'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:
  - mark real first/second visual columns in scroll tables
  - reset only the newly shown table's local scrollLeft on tab switch
  No global wheel/touch interception. */
( function () {
( function () {
'use strict';
'use strict';


function resetShownTableScroll( tab ) {
function markWrappingTables( scope ) {
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 markWrappingTables() {
Array.prototype.forEach.call(
Array.prototype.forEach.call(
document.querySelectorAll( '.mw-parser-output .nv-table-scroll table' ),
scope.querySelectorAll( '.nv-table-scroll table' ),
function ( table ) {
function ( table ) {
if ( table.dataset.nvWrapChecked === '1' ) { return; }
if ( table.dataset.nvWrapChecked === '1' ) { return; }
第1,617行: 第1,393行:
var headerText = ( firstRow.textContent || '' ).replace( /\s+/g, '' );
var headerText = ( firstRow.textContent || '' ).replace( /\s+/g, '' );
var cols = Array.prototype.reduce.call( firstRow.cells, function ( n, cell ) { return n + ( cell.colSpan || 1 ); }, 0 );
var cols = Array.prototype.reduce.call( firstRow.cells, function ( n, cell ) { return n + ( cell.colSpan || 1 ); }, 0 );
if ( cols > 5 || !/(描述|说明|备注)/.test( headerText ) ) { return; }
var longText = Array.prototype.some.call( table.querySelectorAll( 'td' ), function ( cell ) {
var longText = Array.prototype.some.call( table.querySelectorAll( 'td' ), function ( cell ) {
return ( cell.textContent || '' ).trim().length > 60;
return ( cell.textContent || '' ).trim().length > 60;
} );
} );
var descriptionTable = /(描述|说明|备注)/.test( headerText );
if ( ! longText ) { return; }
if ( ! descriptionTable || cols > 5 || ! longText ) { return; }
table.classList.add( 'nv-table--wrap' );
table.classList.add( 'nv-table--wrap' );
var wrap = table.closest( '.nv-table-scroll' );
var wrap = table.closest( '.nv-table-scroll' );
第1,629行: 第1,405行:
}
}


function init() {
mw.hook( 'wikipage.content' ).add( function ( $content ) {
markWrappingTables();
$content.each( function () { markWrappingTables( this ); } );
document.addEventListener( 'click', onTabClick );
} );
}
 
if ( document.readyState === 'loading' ) {
document.addEventListener( 'DOMContentLoaded', init, { once: true } );
} else {
init();
}
}() );
}() );


/* ===== 13: unified footer categories / help / discussion ===== */
/* Source: page-footer.js */
/* Page footer: references, term maintenance and discussion links. */
( function () {
( function () {
'use strict';
'use strict';
if ( !window.mw || !mw.config ) { return; }
if ( !window.mw || !mw.config ) { return; }
var action = mw.config.get( 'wgAction' );
var action = mw.config.get( 'wgAction' );
if ( action !== 'view' || mw.config.get( 'wgNamespaceNumber' ) !== 0 ) { return; }
if ( action !== 'view' || mw.config.get( 'wgNamespaceNumber' ) !== 0 ||
mw.config.get( 'wgDiffNewId' ) !== null ) { return; }
var pageTitle = ( mw.config.get( 'wgPageName' ) || '' ).replace( /_/g, ' ' );
var pageTitle = ( mw.config.get( 'wgPageName' ) || '' ).replace( /_/g, ' ' );
if ( !pageTitle || pageTitle === '首页' || pageTitle === '术语库' || pageTitle === '术语库/编辑' ) { return; }
if ( !pageTitle || pageTitle === '首页' || pageTitle === '术语库' || pageTitle === '术语库/编辑' ) { return; }
第1,653行: 第1,424行:


function closeMenu() {
function closeMenu() {
if ( openMenu ) { openMenu.remove(); openMenu = null; }
if ( openMenu ) {
openMenu.parentNode.querySelector( '[aria-expanded]' ).setAttribute( 'aria-expanded', 'false' );
openMenu.remove();
openMenu = null;
}
}
}


第1,739行: 第1,514行:
if ( heading.closest( '.nv-lock' ) ) { return; }
if ( heading.closest( '.nv-lock' ) ) { return; }
var headline = heading.querySelector( '.mw-headline' );
var headline = heading.querySelector( '.mw-headline' );
var anchor = headline && headline.id;
var anchor = heading.id || ( headline && headline.id );
if ( ! anchor ) { return; }
if ( ! anchor ) { return; }
var label = ( headline.textContent || '' ).trim();
var label = ( headline ? headline.textContent : heading.textContent ).trim();
if ( ! label ) { return; }
if ( ! label ) { return; }
var panel = heading.closest( '.tabber__panel' );
if ( panel ) {
var tab = document.getElementById( panel.getAttribute( 'aria-labelledby' ) );
if ( tab ) { label = tab.textContent.trim() + ' · ' + label; }
}
out.push( { anchor: anchor, label: label } );
out.push( { anchor: anchor, label: label } );
} );
} );
第1,797行: 第1,577行:
footer.className = 'nv-page-footer';
footer.className = 'nv-page-footer';
var help = row( '帮助:' );
var help = row( '帮助:' );
var discussion = row( '讨论:' );
footer.appendChild( help.line );
footer.appendChild( help.line );
footer.appendChild( discussion.line );
footer._help = help.items;
footer._help = help.items;
footer._discussion = discussion.items;
var catlinks = document.getElementById( 'catlinks' );
var catlinks = document.getElementById( 'catlinks' );
if ( catlinks && catlinks.parentNode ) {
if ( catlinks && catlinks.parentNode ) {
第1,809行: 第1,586行:
if ( content ) { content.appendChild( footer ); }
if ( content ) { content.appendChild( footer ); }
}
}
var talkNamespace = ( mw.config.get( 'wgFormattedNamespaces' ) || {} )[ 1 ] || 'Talk';
footer._discussion.appendChild( makeLink( '讨论本页', mw.util.getUrl( talkNamespace + ':' + pageTitle, { action: 'edit', redlink: 1 } ) ) );
footer._discussion.appendChild( makeLink( '弥恩社区', 'https://forum.novark.wiki/' ) );
addSeparators( footer._discussion );
document.addEventListener( 'click', function ( e ) {
document.addEventListener( 'click', function ( e ) {
if ( openMenu && ! openMenu.contains( e.target ) && ! e.target.closest( '.nv-page-footer__menu-wrap' ) ) { closeMenu(); }
if ( openMenu && ! openMenu.contains( e.target ) && ! e.target.closest( '.nv-page-footer__menu-wrap' ) ) { closeMenu(); }
第1,820行: 第1,593行:


function loadTerms() {
function loadTerms() {
return window.nvTermData().then( function ( data ) { return data.terms || []; } );
return window.nvTermCatalog().then( function ( data ) { return data.terms || []; } );
}
}


第1,831行: 第1,604行:
return term.section && norm( term.article ) === norm( pageTitle );
return term.section && norm( term.article ) === norm( pageTitle );
} );
} );
if ( pageLevel ) {
if ( pageLevel && pageLevel.curated ) {
target.appendChild( makeCopyButton( '复制术语引用', nativeRef( pageLevel ) ) );
target.appendChild( makeCopyButton( '复制术语引用', nativeRef( pageLevel ) ) );
target.appendChild( makeLink( '维护术语', mw.util.getUrl( '术语库/编辑', { term: pageLevel.id } ) ) );
target.appendChild( makeLink( '维护术语', mw.util.getUrl( '术语库/编辑', { term: pageLevel.id } ) ) );
第1,846行: 第1,619行:
return { label: section.label, value: '[[' + pageTitle + '#' + section.anchor + '|' + section.label + ']]' };
return { label: section.label, value: '[[' + pageTitle + '#' + section.anchor + '|' + section.label + ']]' };
} ) ) ) );
} ) ) ) );
target.appendChild( makeMenuButton( '创建术语', [ { label: '整页', href: mw.util.getUrl( '术语库/编辑', { name: pageTitle, article: pageTitle } ) } ].concat( list.map( function ( section ) {
if ( pageLevel ) {
target.appendChild( makeLink( '编辑词条', mw.util.getUrl( pageTitle, { action: 'edit' } ) ) );
target.appendChild( makeMenuButton( '别名与章节', [ { label: '整页别名', href: mw.util.getUrl( '术语库/编辑', { name: pageTitle, article: pageTitle } ) } ].concat( list.map( function ( section ) {
return { label: section.label, href: mw.util.getUrl( '术语库/编辑', { name: section.label, article: pageTitle, section: section.anchor } ) };
return { label: section.label, href: mw.util.getUrl( '术语库/编辑', { name: section.label, article: pageTitle, section: section.anchor } ) };
} ) ) ) );
} ) ) ) );
}
}
}
target.appendChild( makeLink( '历史', mw.util.getUrl( 'Special:History/' + pageTitle ) ) );
target.appendChild( makeLink( '历史', mw.util.getUrl( 'Special:History/' + pageTitle ) ) );
第1,864行: 第1,640行:
}() );
}() );


/* Rule version: preference and single-button view over native TabberNeue.
/* Source: page-status.js */
   Any explicit section/hash wins over the saved preference. */
/* ==========================================================================
  Page status banners: read the page's categories and render framed
  status banners at the top of the article. The
  templates only categorise; the visual layer lives here and in
   Template:状态/styles.css.
  ========================================================================== */
( function () {
( function () {
'use strict';
'use strict';
var STORAGE_KEY = 'novarkRuleVersion';
var VERSIONS = [ '3.5E', '5.5E' ];
var RULE_HASH = /^#tabber-DND_(3\.5E|5\.5E)$/;
var applyingPreference = false;


function getPreference() {
var STATUS = {
try {
'剧透': { icon: 'spoiler', tone: 'spoiler', title: '剧透', text: '此页面包含剧透内容,可能涉及尚未公开的跑团剧情、角色结局或重要谜底,请谨慎阅读。' },
var value = window.localStorage.getItem( STORAGE_KEY );
'非正史': { icon: 'noncanon', tone: 'noncanon', title: '非正史', text: '当前页面属于非正史内容,可作为衍生创作参考,但不自动进入主设定。' },
return VERSIONS.indexOf( value ) >= 0 ? value : null;
'跑团记录': { icon: 'campaign', tone: 'campaign', title: '跑团记录', text: '当前页面为跑团记录,内容首先属于对应战役的推演记录;若需进入主设定,应另行经过引入流程。' },
} catch ( e ) {
'消歧义': { icon: 'disambiguation', tone: 'disambiguation', title: '消歧义', text: '当前页面是消歧义页,用于罗列标题相同或相近、但内容不同的条目。' },
return null;
'修订中': { icon: 'revising', tone: 'revising', title: '修订中', text: '当前页面正在修订,内容可能继续调整。' },
}
'确认中': { icon: 'confirming', tone: 'confirming', title: '确认中', text: '当前页面的内容正在讨论或核对,相关结论尚待确认。' },
}
'已锚定': { icon: 'anchored', tone: 'anchored', title: '已锚定', text: '当前页面所描述的设定已被锚定,可以自由参考和引用;修改事实性内容前,请先依照共创指南发起讨论。' },
'需要改进': { icon: 'improve', tone: 'improve', title: '需要改进', text: '当前页面仍需改进,欢迎补充内容、修改措辞和完善链接。' },
'精选': { icon: 'featured', tone: 'featured', title: '精选', text: '此页面被标记为精选内容,可作为同类条目的高质量参考。' }
};


function setPreference( version ) {
var STATUS_ORDER = [ '剧透', '非正史', '跑团记录', '确认中', '修订中', '需要改进', '已锚定', '精选', '消歧义' ];
try {
window.localStorage.setItem( STORAGE_KEY, version );
} catch ( e ) {
// localStorage may be unavailable; preference is best-effort only.
}
}


function findRuleTabber() {
function sourceFor( content, kind, type ) {
var tabbers = document.querySelectorAll( '.tabber' );
var nodes = content.querySelectorAll( '.nv-status-source' );
for ( var i = 0; i < tabbers.length; i++ ) {
for ( var i = 0; i < nodes.length; i++ ) {
if ( isRuleTabber( tabbers[ i ] ) && tabsOf( tabbers[ i ] ).length === 2 ) {
if ( nodes[ i ].getAttribute( 'data-nv-kind' ) === kind &&
return tabbers[ i ];
nodes[ i ].getAttribute( 'data-nv-type' ) === type ) {
return nodes[ i ];
}
}
}
}
第1,900行: 第1,675行:
}
}


function tabForVersion( tabber, version ) {
function appendSource( body, source ) {
var tabs = tabsOf( tabber );
if ( !source ) { return; }
for ( var i = 0; i < tabs.length; i++ ) {
[ 'note', 'discuss' ].forEach( function ( suffix ) {
if ( tabs[ i ].getAttribute( 'href' ) === '#tabber-DND_' + version ) {
var sourceEl = source.querySelector( '.nv-status-' + suffix );
return tabs[ i ];
if ( !sourceEl ) { return; }
var box = document.createElement( 'div' );
box.className = 'nv-status-banner__' + suffix;
Array.prototype.forEach.call( sourceEl.childNodes, function ( node ) { box.appendChild( node.cloneNode( true ) ); } );
if ( box.textContent.trim() || box.querySelector( 'a' ) ) {
body.appendChild( box );
}
}
}
} );
return null;
}
 
function activeVersion( tabber ) {
var tabs = tabsOf( tabber );
for ( var i = 0; i < tabs.length; i++ ) {
if ( tabs[ i ].getAttribute( 'aria-selected' ) === 'true' ) {
var match = ( tabs[ i ].getAttribute( 'href' ) || '' ).match( RULE_HASH );
if ( match ) {
return match[ 1 ];
}
}
}
return null;
}
}


function versionHasContent( tabber, version ) {
function makeBanner( def, source ) {
if ( !tabForVersion( tabber, version ) ) {
var banner = document.createElement( 'div' );
return false;
banner.className = 'nv-status-banner nv-status-banner--' + def.tone;
}
// NB: panel ids contain a dot ("tabber-DND_5.5E"), which is not a valid
// CSS identifier inside a selector string; use getElementById instead.
var panel = document.getElementById( 'tabber-DND_' + version );
if ( !panel || !tabber.contains( panel ) ) {
// TabberNeue panels may live under a section wrapper; fall back to the tab.
return true;
}
// {{规则分版}} emits this placeholder for a missing version subpage.
var text = ( panel.textContent || '' ).replace( /\s+/g, '' );
return text.indexOf( '本版规则尚未补充' ) === -1;
}
 
function applyPreference() {
if ( applyingPreference ) {
return;
}
// Explicit anchor (rule or ordinary section) always wins; do not touch it.
if ( window.location.hash ) {
return;
}
var preference = getPreference();
if ( !preference ) {
return;
}
var tabber = findRuleTabber();
if ( !tabber || activeVersion( tabber ) === preference ) {
return;
}
// Do not hide the page's actual content behind a not-yet-created version.
if ( !versionHasContent( tabber, preference ) ) {
return;
}
var tab = tabForVersion( tabber, preference );
if ( !tab ) {
return;
}
applyingPreference = true;
try {
tab.click(); // reuse TabberNeue's own click handling
} finally {
applyingPreference = false;
}
}
 
function scheduleApply() {
if ( !document.querySelector( '.tabber' ) ) { return; }
var tries = 0;
( function tick() {
var tabber = findRuleTabber();
if ( tabber ) {
var initialised = tabsOf( tabber ).some( function ( tab ) {
return tab.hasAttribute( 'aria-selected' );
} );
if ( initialised ) {
applyPreference();
return;
}
}
if ( tries++ < 30 ) {
window.setTimeout( tick, 100 );
}
}() );
}
 
// Write preference only for real user clicks on a rule-version tab.
document.addEventListener( 'click', function ( event ) {
if ( applyingPreference ) {
return;
}
var tab = event.target && event.target.closest ?
event.target.closest( '.tabber__tabs a.tabber__tab' ) :
null;
if ( !tab ) {
return;
}
var tabber = tab.closest( '.tabber' );
if ( !isRuleTabber( tabber ) ) {
return;
}
var match = ( tab.getAttribute( 'href' ) || '' ).match( RULE_HASH );
if ( match ) {
setPreference( match[ 1 ] );
}
}, true );
 
window.addEventListener( 'pageshow', function () {
window.setTimeout( applyPreference, 0 );
} );
 
var VERSION_HASH = /#tabber-DND_(3\.5E|5\.5E)/;
var ICON_SLOT = 'rule-version';
 
function tabsOf( tabber ) {
return Array.prototype.slice.call( tabber.querySelectorAll( '.tabber__tabs a.tabber__tab' ) );
}
function versionOf( tab ) {
var match = ( tab.getAttribute( 'href' ) || '' ).match( VERSION_HASH );
return match ? match[ 1 ] : null;
}
function iconKey( version ) {
if ( version === '3.5E' ) { return 'rule-35'; }
if ( version === '5.5E' ) { return 'rule-55'; }
return 'rule-common';
}
function labelOf( tab ) {
return ( tab.textContent || '' ).replace( /\s+/g, ' ' ).trim();
}
function currentTab( tabber ) {
var tabs = tabsOf( tabber );
for ( var i = 0; i < tabs.length; i++ ) {
if ( tabs[ i ].getAttribute( 'aria-selected' ) === 'true' ) { return tabs[ i ]; }
}
return tabs[ 0 ] || null;
}
function isRuleTabber( tabber ) {
var tabs = tabsOf( tabber );
if ( ! tabs.length ) { return false; }
if ( tabs.length > 2 ) { return false; }
return tabs.every( function ( tab ) { return !! versionOf( tab ); } );
}
function closeMenus() {
document.querySelectorAll( '.nv-rule-version__menu' ).forEach( function ( menu ) { menu.remove(); } );
document.querySelectorAll( '.nv-rule-version__button[aria-expanded="true"]' ).forEach( function ( button ) {
button.setAttribute( 'aria-expanded', 'false' );
} );
}
function positionMenu( menu, button ) {
var margin = 12, vw = innerWidth, vh = innerHeight;
menu.style.width = Math.min( 250, vw - margin * 2 ) + 'px';
menu.style.maxHeight = Math.min( 260, vh - margin * 2 ) + 'px';
var br = button.getBoundingClientRect();
var rect = menu.getBoundingClientRect();
var left = Math.max( margin, Math.min( br.left, vw - margin - rect.width ) );
var below = vh - br.bottom - margin;
var above = br.top - margin;
var top = ( below >= Math.min( rect.height, 180 ) || below >= above ) ? br.bottom + 6 : br.top - 6 - rect.height;
top = Math.max( margin, Math.min( top, vh - margin - rect.height ) );
menu.style.left = Math.round( left ) + 'px';
menu.style.top = Math.round( top ) + 'px';
}
function build( tabber ) {
if ( tabber.dataset.nvRuleVersion === '1' ) { return; }
tabber.dataset.nvRuleVersion = '1';
var tabs = tabsOf( tabber );
var single = tabs.length === 1;
var header = tabber.querySelector( '.tabber__header' );
var control = document.createElement( single ? 'span' : 'div' );
control.className = 'nv-rule-version' + ( single ? ' nv-rule-version--static' : '' );
control.setAttribute( 'data-icon-slot', ICON_SLOT );
control.setAttribute( 'data-version', '' );
var icon = document.createElement( 'span' );
var icon = document.createElement( 'span' );
icon.className = 'nv-rule-version__icon';
icon.className = 'nv-status-banner__icon nv-icon nv-icon--' + def.icon;
icon.setAttribute( 'data-icon-slot', ICON_SLOT );
icon.setAttribute( 'data-icon-key', 'rule-common' );
icon.setAttribute( 'aria-hidden', 'true' );
icon.setAttribute( 'aria-hidden', 'true' );
var label = document.createElement( 'span' );
var body = document.createElement( 'div' );
label.className = 'nv-rule-version__label';
body.className = 'nv-status-banner__body';
var button = null;
var title = document.createElement( 'strong' );
if ( ! single ) {
title.className = 'nv-status-banner__title';
button = document.createElement( 'button' );
title.textContent = def.title;
button.type = 'button';
body.appendChild( title );
button.className = 'nv-rule-version__button';
if ( def.text ) {
button.setAttribute( 'aria-haspopup', 'menu' );
var text = document.createElement( 'span' );
button.setAttribute( 'aria-expanded', 'false' );
text.className = 'nv-status-banner__text';
button.setAttribute( 'data-icon-slot', ICON_SLOT );
text.textContent = def.text;
button.appendChild( icon );
body.appendChild( text );
button.appendChild( label );
var chevron = document.createElement( 'span' );
chevron.className = 'nv-rule-version__chevron';
chevron.setAttribute( 'aria-hidden', 'true' );
chevron.textContent = '▾';
button.appendChild( chevron );
control.appendChild( button );
} else {
control.appendChild( icon );
control.appendChild( label );
}
}
tabber.insertBefore( control, header || tabber.firstChild );
appendSource( body, source );
tabber.classList.add( 'nv-rule-version-enhanced' );
banner.appendChild( icon );
banner.appendChild( body );
return banner;
}


function sync() {
function render( $content ) {
var tab = currentTab( tabber );
if ( !document.body || !document.body.classList.contains( 'action-view' ) ) { return; }
if ( ! tab ) { return; }
if ( !window.mw || !mw.config || mw.config.get( 'wgNamespaceNumber' ) !== 0 ||
var version = versionOf( tab );
mw.config.get( 'wgDiffNewId' ) !== null ) { return; }
control.setAttribute( 'data-version', version || 'common' );
var content = document.querySelector( '#mw-content-text .mw-parser-output' );
control.setAttribute( 'data-icon-key', iconKey( version ) );
if ( !content || !$content.toArray().some( function ( root ) { return root === content || root.contains( content ); } ) ) { return; }
icon.setAttribute( 'data-icon-key', iconKey( version ) );
var old = content.querySelector( '[data-nv-status-banner]' );
label.textContent = labelOf( tab );
var cats = mw.config.get( 'wgCategories' ) || [];
if ( button ) { button.setAttribute( 'aria-label', '当前规则版本:' + labelOf( tab ) + ',选择其他版本' ); }
var signature = JSON.stringify( cats );
if ( control.querySelector( '.nv-rule-version__menu' ) ) {
if ( old && old.getAttribute( 'data-nv-categories' ) === signature ) { return; }
control.querySelectorAll( '.nv-rule-version__item' ).forEach( function ( item ) {
if ( old ) { old.remove(); }
item.setAttribute( 'aria-current', item.getAttribute( 'data-version' ) === version ? 'true' : 'false' );
var nodes = [];
} );
var i;
for ( i = 0; i < STATUS_ORDER.length; i++ ) {
if ( cats.indexOf( STATUS_ORDER[ i ] ) !== -1 ) {
nodes.push( makeBanner( STATUS[ STATUS_ORDER[ i ] ], sourceFor( content, 'status', STATUS_ORDER[ i ] ) ) );
break;
}
}
}
}
if ( !nodes.length ) { return; }


if ( button ) {
var stack = document.createElement( 'div' );
button.addEventListener( 'click', function ( e ) {
stack.className = 'nv-status-stack';
e.stopPropagation();
stack.setAttribute( 'data-nv-status-banner', '' );
if ( button.getAttribute( 'aria-expanded' ) === 'true' ) { closeMenus(); return; }
stack.setAttribute( 'data-nv-categories', signature );
closeMenus();
nodes.forEach( function ( node ) { stack.appendChild( node ); } );
var menu = document.createElement( 'div' );
content.insertBefore( stack, content.firstChild );
menu.className = 'nv-rule-version__menu';
menu.setAttribute( 'role', 'menu' );
tabs.forEach( function ( tab ) {
var item = document.createElement( 'button' );
item.type = 'button';
item.className = 'nv-rule-version__item';
item.setAttribute( 'role', 'menuitem' );
var itemVersion = versionOf( tab ) || 'common';
item.setAttribute( 'data-version', itemVersion );
item.setAttribute( 'aria-current', itemVersion === ( versionOf( currentTab( tabber ) ) || 'common' ) ? 'true' : 'false' );
item.textContent = labelOf( tab );
item.addEventListener( 'click', function () {
closeMenus();
tab.click();
window.setTimeout( sync, 20 );
} );
menu.appendChild( item );
} );
control.appendChild( menu );
button.setAttribute( 'aria-expanded', 'true' );
positionMenu( menu, button );
var first = menu.querySelector( '.nv-rule-version__item[aria-current="true"], .nv-rule-version__item' );
if ( first ) { first.focus( { preventScroll: true } ); }
} );
control.addEventListener( 'keydown', function ( e ) {
if ( e.key === 'Escape' ) { closeMenus(); button.focus(); }
} );
}
var nav = tabber.querySelector( '.tabber__tabs' );
if ( nav && window.MutationObserver ) {
new MutationObserver( sync ).observe( nav, { subtree: true, attributes: true, attributeFilter: [ 'aria-selected' ] } );
}
window.addEventListener( 'hashchange', function () { window.setTimeout( sync, 40 ); } );
window.addEventListener( 'pageshow', function () { window.setTimeout( sync, 40 ); } );
sync();
}
}


document.addEventListener( 'click', function ( e ) {
mw.hook( 'wikipage.content' ).add( render );
if ( ! e.target.closest( '.nv-rule-version' ) ) { closeMenus(); }
}, true );
 
function start() {
document.querySelectorAll( '.tabber' ).forEach( function ( tabber ) {
if ( isRuleTabber( tabber ) ) { build( tabber ); }
} );
scheduleApply();
}
if ( document.readyState === 'loading' ) { document.addEventListener( 'DOMContentLoaded', start, { once: true } ); }
else { start(); }
window.addEventListener( 'pageshow', function () { window.setTimeout( start, 80 ); } );
}() );
}() );

2026年11月16日 (一) 16:43的最新版本

/* Generated from site-scripts/common. Edit the source files, not this bundle. */

/* Source: page-tools.js */
/* Page tools: table-backed calculators and spell filters.
 * 自定义控件由本脚本创建;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(scope, id) {
    var table = scope.querySelector('#' + 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(scope) {
    return {
      alpha: economyRows(scope, 'nv-economy-alpha').map(function (r) { return [r[0], { alpha: economyNumber(r[1]) }]; }),
      beta: economyRows(scope, 'nv-economy-beta').map(function (r) { return [r[0], { beta: economyNumber(r[1]), limit: economyNumber(r[2]) }]; }),
      gamma: economyRows(scope, 'nv-economy-gamma').map(function (r) { return [r[0], { gamma: economyNumber(r[1]) }]; }),
      currencies: economyRows(scope, '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 bindControls(controls, update) {
    controls.forEach(function (control) {
      control.addEventListener(control.tagName === 'SELECT' ? 'change' : 'input', update);
    });
    update();
  }

  function buildPriceUI(host, data) {
    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));
    var result = host.querySelector('#mien-price-result');
    var limit = host.querySelector('#mien-price-limit');
    var formula = host.querySelector('#mien-price-formula');

    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);
      result.textContent = formatNumber(finalPrice) + ' ' + currencyName + '(' + formatNumber(gp) + ' GP)';
      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'); }
      formula.textContent =
        '实际价值:ω* = ω0 × α × β × γ = ' + formatNumber(baseValue) + ' GP × ' + a + ' × ' + b + ' × ' + g +
        ' = ' + formatNumber(gp) + ' GP。结算价格:ω = ω* × δ* = ' + formatNumber(gp) + ' GP × ' + rate +
        ' = ' + formatNumber(finalPrice) + ' ' + currencyName + '。';
    }
    bindControls([base, alpha, beta, gamma, currency], update);
  }

  function buildCreditUI(host, data) {
    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, '选项来自下方货币表;未标明汇率的独立本位币不参与换算。'));
    var result = host.querySelector('#mien-credit-result');
    var nominalResult = host.querySelector('#mien-credit-nominal-result');
    var marketResult = host.querySelector('#mien-credit-market-result');
    var formula = host.querySelector('#mien-credit-formula');

    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;
      result.textContent = formatNumber(targetAmount) + ' ' + currencyName(target);
      nominalResult.textContent = formatNumber(snGp);
      marketResult.textContent = formatNumber(smGp);
      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) + '。';
    }
    bindControls([amount, source, target], update);
  }

  function spellNoValue(value) {
    var text = String(value || '').trim();
    return !text || text === '-' || text === '—' || text === '无' ? '无' : text;
  }

  // Read each cell once. Filters retain row nodes, so native sorting can move them freely.
  function readSpellRows(table) {
    return Array.from(table.rows).filter(function (row) {
      return row.cells.length && row.cells[0].tagName === 'TD';
    }).map(function (row) {
      var cells = Array.from(row.cells, function (cell) { return cell.textContent.trim(); });
      return {
        element: row,
        searchText: cells.join(' ').toLowerCase(),
        className: spellNoValue(cells[3]),
        level: (cells[1] || '').replace(/\s*级$/, '').trim(),
        school: cells[2] || '',
        domain: spellNoValue(cells[4])
      };
    });
  }

  function spellSelect(id, labelText, values, optionLabel) {
    var select = el('select', { id: id, 'aria-label': labelText });
    select.appendChild(el('option', { value: '' }, '全部' + labelText));
    Array.from(new Set(values)).filter(Boolean).forEach(function (value) {
      select.appendChild(el('option', { value: value }, optionLabel ? optionLabel(value) : value));
    });
    return select;
  }

  function buildSpellUI(host, table) {
    host.dataset.built = 'true';
    host.classList.add('mien-spell-filter');
    var rows = readSpellRows(table);
    var classes = rows.reduce(function (values, row) {
      return values.concat(row.className, row.className.split(/[\/、,,]/).map(function (value) { return value.trim(); }));
    }, []);
    var levels = rows.map(function (row) { return row.level; }).sort(function (a, b) { return Number(a) - Number(b); });
    var search = el('input', { id: 'spell-search', type: 'search', placeholder: '搜索法术名称、简述、学派…', 'aria-label': '搜索法术' });
    var classFilter = spellSelect('spell-class-filter', '法表', classes);
    var levelFilter = spellSelect('spell-level-filter', '等级', levels, function (value) { return value + ' 级'; });
    var schoolFilter = spellSelect('spell-school-filter', '学派', rows.map(function (row) { return row.school; }));
    var domainFilter = spellSelect('spell-domain-filter', '领域', rows.map(function (row) { return row.domain; }), function (value) { return value === '无' ? '无领域' : value; });
    var controls = [search, classFilter, levelFilter, schoolFilter, domainFilter];
    var clear = el('button', { type: 'button', id: 'spell-clear' }, '清除条件');
    controls.concat(clear).forEach(function (control) { host.appendChild(control); });

    function applyFilters() {
      var query = search.value.trim().toLowerCase();
      rows.forEach(function (row) {
        var matches = (!query || row.searchText.indexOf(query) !== -1) &&
          (!classFilter.value || row.className.indexOf(classFilter.value) !== -1) &&
          (!levelFilter.value || row.level === levelFilter.value) &&
          (!schoolFilter.value || row.school === schoolFilter.value) &&
          (!domainFilter.value || row.domain === domainFilter.value);
        row.element.hidden = !matches;
        row.element.classList.toggle('mien-spell-row-hidden', !matches);
      });
    }

    bindControls(controls, applyFilters);
    clear.addEventListener('click', function () {
      controls.forEach(function (control) { control.value = ''; });
      applyFilters();
    });

    // MediaWiki owns sorting, keyboard access and direction indicators.
    rows.forEach(function (row) { row.element.cells[1].dataset.sortValue = row.level; });
    table.classList.add('sortable');
    mw.loader.using('jquery.tablesorter').then(function () {
      if (table.isConnected) { $(table).tablesorter(); }
    });
  }

  function initPageTools(scope) {
    var price = scope.querySelector('#mien-price-calculator:not([data-built="true"])');
    var credit = scope.querySelector('#mien-credit-currency-calculator:not([data-built="true"])');
    if (price || credit) {
      var economy = readEconomyData(scope);
      if (economy.alpha.length && economy.beta.length && economy.gamma.length && economy.currencies.length) {
        if (price) { buildPriceUI(price, economy); }
        if (credit) { buildCreditUI(credit, economy); }
      } else {
        [price, credit].filter(Boolean).forEach(function (host) {
          host.textContent = '计算器需要本页完整的物价系数表和货币汇率表。';
        });
      }
    }
    var spellHost = scope.querySelector('#spell-filter-host:not([data-built="true"])');
    var spellTable = spellHost && scope.querySelector('.mien-spell-table');
    if (spellHost && spellTable) { buildSpellUI(spellHost, spellTable); }
  }

  // The hook remembers the initial content and also receives newly rendered fragments.
  mw.hook('wikipage.content').add(function ($content) {
    $content.each(function () { initPageTools(this); });
  });
}());

/* Source: clipboard.js */
/* Shared clipboard action for the page footer and glossary editor. */
window.nvCopyText = function (value, button) {
  var old = button.getAttribute('data-label') || button.textContent;
  function done() {
    button.textContent = '已复制';
    window.setTimeout(function () { button.textContent = old; }, 1200);
  }
  function fallback() {
    var area = document.createElement('textarea');
    area.value = value;
    area.setAttribute('readonly', '');
    area.style.position = 'fixed';
    area.style.left = '-9999px';
    document.body.appendChild(area);
    area.select();
    var copied = false;
    try { copied = document.execCommand('copy'); } catch (err) { copied = false; }
    document.body.removeChild(area);
    if (copied) { done(); return; }
    var input = button.parentNode && button.parentNode.querySelector('.nv-copy-fallback');
    if (input) { input.remove(); }
    input = document.createElement('input');
    input.className = 'nv-copy-fallback';
    input.readOnly = true;
    input.value = value;
    input.setAttribute('aria-label', '复制失败,请手动选择文字');
    if (button.parentNode) { button.parentNode.insertBefore(input, button.nextSibling); }
    input.focus();
    input.select();
    button.textContent = '请手动复制';
    window.setTimeout(function () { if (input.isConnected) { input.remove(); } button.textContent = old; }, 12000);
  }
  if (navigator.clipboard && navigator.clipboard.writeText && window.isSecureContext) {
    navigator.clipboard.writeText(value).then(done, fallback);
  } else {
    fallback();
  }
};

/* Source: term-catalog.js */
/* Shared cached loader for the term JSON index (read-only consumers: NvLock preview
   and the unified page footer). The editor keeps its own uncached fetch to read the
   latest revision + basetimestamp for conflict-safe saves. */
window.nvTermData = ( function () {
	var cached = null, loading = null;
	return function () {
		if ( cached ) { return Promise.resolve( cached ); }
		if ( loading ) { return loading; }
		var url = mw.util.getUrl( 'Module:术语库/data.json', { action: 'raw' } );
		loading = fetch( url, { credentials: 'same-origin' } ).then( function ( r ) {
			if ( !r.ok ) { throw new Error( 'terms-' + r.status ); }
			return r.json();
		} ).then( function ( data ) {
			cached = data;
			loading = null;
			return data;
		} ).catch( function ( err ) {
			loading = null;
			throw err;
		} );
		return loading;
	};
}() );

/* Page-backed terms. Native pages/categories/redirects are the catalogue; the
   existing JSON supplies compatible IDs, explicit aliases and section entries. */
window.nvTermCatalog = ( function () {
	'use strict';
	var cached, loading, loadedAt = 0;
	var excluded = new Set( [ '索引页面', '站点导航', '帮助与指南' ] );
	var maintenance = new Set( [ '术语', '资料', '已锚定', '需要改进', '待改进', '剧透' ] );
	function norm( value ) { return String( value || '' ).replace( /_/g, ' ' ).trim().toLowerCase(); }
	function readPages( force ) {
		var pages = new Map(), api = new mw.Api();
		function read( continuation ) {
			return api.get( Object.assign( {
				action: 'query', formatversion: 2, generator: 'allpages', gapnamespace: 0,
				// Native browser caching also covers navigation between articles.
				maxage: force ? 0 : 60,
				gapfilterredir: 'nonredirects', gaplimit: 'max',
				prop: 'info|categories|redirects|pageprops', inprop: 'url',
				cllimit: 'max', rdlimit: 'max', rdnamespace: 0, rdprop: 'title|fragment',
				ppprop: 'disambiguation'
			}, continuation || {} ) ).then( function ( result ) {
				( result.query && result.query.pages || [] ).forEach( function ( page ) {
					var old = pages.get( page.pageid );
					if ( old ) {
						page.categories = ( old.categories || [] ).concat( page.categories || [] );
						page.redirects = ( old.redirects || [] ).concat( page.redirects || [] );
					}
					pages.set( page.pageid, page );
				} );
				return result.continue ? read( result.continue ) : Array.from( pages.values() );
			} );
		}
		return read();
	}
	function combine( pages, metadata ) {
		var terms = [], targets = Object.create( null ), order = ( metadata.categoryOrder || [] ).slice();
		pages.forEach( function ( page ) {
			var categories = Array.from( new Set( ( page.categories || [] ).map( function ( cat ) {
				return cat.title.replace( /^(Category|分类):/, '' );
			} ) ) );
			if ( page.missing || page.ns !== 0 || !page.length || page.pageprops &&
				Object.prototype.hasOwnProperty.call( page.pageprops, 'disambiguation' ) ||
				categories.some( function ( cat ) { return excluded.has( cat ); } ) ||
				[ '首页', '术语库', '术语库/编辑', '作者入口' ].indexOf( page.title ) >= 0 ) { return; }
			var term = {
				id: 'page-' + page.pageid, pageid: page.pageid, revid: page.lastrevid,
				name: page.title, article: page.title, aliases: [], legacyIds: [],
				categories: categories.filter( function ( cat ) { return !maintenance.has( cat ) && !/^使用.*的页面$/.test( cat ); } )
			};
			( page.redirects || [] ).forEach( function ( redirect ) {
				if ( !redirect.fragment ) { term.aliases.push( redirect.title ); }
			} );
			terms.push( term );
			[ page.title ].concat( term.aliases ).forEach( function ( title ) { targets[ norm( title ) ] = term; } );
		} );
		( metadata.terms || [] ).forEach( function ( record ) {
			var page = targets[ norm( record.article || record.name ) ];
			if ( !page ) { return; }
			var term = page;
			if ( record.section ) {
				term = Object.assign( {}, record, { pageid: page.pageid, article: page.article, categories: record.categories || [], legacyIds: [], curated: true } );
				terms.push( term );
			} else {
				if ( !term.curated ) { term.id = record.id; }
				term.curated = true;
			}
			term.legacyIds.push( record.id );
			term.categories = Array.from( new Set( term.categories.concat( record.categories || [] ) ) );
			term.aliases = Array.from( new Set( ( term.aliases || [] ).concat( record.aliases || [], record.name || [] ) ) )
				.filter( function ( alias ) { return norm( alias ) !== norm( term.name ); } );
		} );
		terms.forEach( function ( term ) {
			term.categories.forEach( function ( category ) { if ( order.indexOf( category ) < 0 ) { order.push( category ); } } );
		} );
		return { terms: terms, categoryOrder: order, automatic: true };
	}
	return function ( force ) {
		if ( !force && cached && Date.now() - loadedAt < 60000 ) { return Promise.resolve( cached ); }
		if ( loading ) { return loading; }
		loading = mw.loader.using( [ 'mediawiki.api', 'mediawiki.util' ] ).then( function () {
			return Promise.all( [ readPages( force ), window.nvTermData().catch( function () { return { terms: [] }; } ) ] );
		} )
			.then( function ( values ) { cached = combine( values[ 0 ], values[ 1 ] ); loadedAt = Date.now(); loading = null; return cached; },
				function ( error ) { loading = null; throw error; } );
		return loading;
	};
}() );

/* Source: term-preview.js */
/* ==========================================================================
   Term preview: progressive reading chains backed by canonical page content.
   - 真实 800ms 进度;满圈才 locked,可移入
   - 根词 180ms 延迟;未满圈离开立即取消
   - 每层以当次触发鼠标坐标为锚,不排队;卡片内容按规范词条正文加载(有界卡内可读)
   - 无深度上限;窄屏单面板可继续深入
   ========================================================================== */
( function () {
	'use strict';
	// Previews belong to reading pages, not navigation or revision tools.
	if ( mw.config.get( 'wgIsMainPage' ) || mw.config.get( 'wgAction' ) !== 'view' ||
		mw.config.get( 'wgDiffNewId' ) !== null || mw.config.get( 'wgNamespaceNumber' ) < 0 ) { return; }

	function boot() {
		if ( window.NvLock || !document.querySelector( '#mw-content-text .mw-parser-output' ) ) { return; }

		var CFG = {
			rootDelay: 180,
			childDelay: 170,
			lockMs: 800,
			gap: 10,
			width: 480,
			wideWidth: 620,
			grace: 160,
			lockedGrace: 430
		};
		var reduceMotion = window.matchMedia && window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches;
		var coarse = window.matchMedia && window.matchMedia( '(hover: none), (pointer: coarse)' ).matches;
		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,
			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 ) { var u = mw.util.getUrl( term.article ); return term.section ? u + '#' + encodeURIComponent( term.section ) : u; }
			return mw.util.getUrl( '术语库' ) + '#' + term.id;
		}
		function isNavigationLink( a ) {
			return !! closest( a, '.nv-chapter-nav, .nv-home, .nv-card, .toc, .catlinks, .printfooter' );
		}

		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|Help|User|Project|Draft|Gadget):/i.test( title ) ) { return null; }
			try {
				if ( mw.Title && new mw.Title( title ).namespace !== 0 ) { return null; }
			} catch ( err ) { 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 fetchTerms() {
			if ( termIndex ) { return Promise.resolve( termIndex ); }
			if ( termLoading ) { return termLoading; }
			termLoading = window.nvTermCatalog().then( function ( data ) {
				var byId = Object.create( null );
				var byTitle = Object.create( null );
				var byArticle = Object.create( null );
				var bySection = Object.create( null );
				var unique = Object.create( null );
				( data.terms || [] ).forEach( function ( t ) {
					byId[ t.id ] = t;
					( t.legacyIds || [] ).forEach( function ( id ) { byId[ id ] = t; } );
					if ( t.article && ! t.section ) { byArticle[ norm( t.article ) ] = t; }
					if ( t.section ) { bySection[ norm( t.article || t.name ) + '#' + norm( t.section ) ] = t; }
					[ t.name ].concat( t.aliases || [] ).forEach( function ( n ) {
						var key = norm( n );
						if ( !key ) { return; }
						if ( Object.prototype.hasOwnProperty.call( byTitle, key ) && ( !byTitle[ key ] || byTitle[ key ].id !== t.id ) ) { byTitle[ key ] = null; }
						else { byTitle[ key ] = t; }
						if ( t.curated ) {
							if ( Object.prototype.hasOwnProperty.call( unique, key ) && ( !unique[ key ] || unique[ key ].id !== t.id ) ) { unique[ key ] = null; }
							else { unique[ key ] = t; }
						}
					} );
				} );
				// Longest match first, grouped once by initial character. Ambiguous names stay excluded.
				var matchesByInitial = Object.create( null );
				Object.keys( unique ).filter( function ( key ) { return !! unique[ key ]; } )
					.sort( function ( a, b ) { return b.length - a.length; } )
					.forEach( function ( key ) {
						var initial = key.charAt( 0 );
						if ( !matchesByInitial[ initial ] ) { matchesByInitial[ initial ] = []; }
						matchesByInitial[ initial ].push( { key: key, term: unique[ key ] } );
					} );
				termIndex = { byId: byId, byTitle: byTitle, byArticle: byArticle, bySection: bySection, matchesByInitial: matchesByInitial, raw: data };
				return termIndex;
			} ).catch( function ( err ) {
				console.warn( 'NvLock terms load failed', err );
				termLoading = null;
				throw err;
			} );
			return termLoading;
		}

		/* Preview the canonical page or requested section in full.
		   Parsed content keeps its own styles and extension modules. */
		var articleCache = Object.create( null );
		var articleLoading = Object.create( null );
		var previewSequence = 0;

		// Full articles can contain the same section/tab IDs as the host page or another card.
		function scopePreview( article, body, title, section ) {
			var prefix = 'nv-preview-' + ( ++previewSequence ) + '-';
			var ids = new Map();
			article.querySelectorAll( '[id]' ).forEach( function ( element ) {
				ids.set( element.id, prefix + element.id ); element.id = prefix + element.id;
			} );
			article.querySelectorAll( '[aria-controls],[aria-labelledby],[aria-describedby],[for]' ).forEach( function ( element ) {
				[ 'aria-controls', 'aria-labelledby', 'aria-describedby', 'for' ].forEach( function ( attr ) {
					if ( element.hasAttribute( attr ) ) {
						element.setAttribute( attr, element.getAttribute( attr ).split( /\s+/ ).map( function ( id ) { return ids.get( id ) || id; } ).join( ' ' ) );
					}
				} );
			} );
			article.querySelectorAll( 'a[href]' ).forEach( function ( link ) {
				var raw = link.getAttribute( 'href' ), target = targetOf( link );
				var fragment = raw.charAt( 0 ) === '#' ? mw.util.percentDecodeFragment( raw.slice( 1 ) ) :
					( target && norm( target.title ) === norm( title ) ? target.hash : '' );
				if ( ids.has( fragment ) ) { link.setAttribute( 'href', '#' + ids.get( fragment ) ); }
			} );
			var pending = null;
			function scrollTarget() {
				if ( !pending ) { return; }
				body.scrollTop += pending.getBoundingClientRect().top - body.getBoundingClientRect().top;
				pending = null;
			}
			function jump( target ) {
				pending = target;
				var panel = target.closest( '.tabber__panel' );
				var tab = panel && article.querySelector( '[aria-controls="' + CSS.escape( panel.id ) + '"]' );
				if ( tab && tab.getAttribute( 'aria-selected' ) !== 'true' ) { tab.click(); }
				else { scrollTarget(); }
			}
			article.addEventListener( 'tabber:tabchange', function ( event ) {
				// The extension owns switching; a card must not rewrite the host page's fragment.
				event.stopPropagation();
				if ( pending ) { requestAnimationFrame( scrollTarget ); }
				if ( event.detail.source === 'init' && ids.has( section ) ) {
					var target = article.querySelector( '#' + CSS.escape( ids.get( section ) ) );
					section = '';
					queueMicrotask( function () { jump( target ); } );
				}
			} );
			article.addEventListener( 'click', function ( event ) {
				var link = event.target.closest( 'a[href^="#' + prefix + '"]' );
				if ( !link || link.classList.contains( 'tabber__tab' ) || event.ctrlKey || event.metaKey || event.shiftKey ) { return; }
				var target = article.querySelector( '#' + CSS.escape( mw.util.percentDecodeFragment( link.hash.slice( 1 ) ) ) );
				if ( target ) { event.preventDefault(); jump( target ); }
			} );
		}

		function articleTitleOf( term ) {
			return term.article || term.name;
		}

		function applyPreviewReadingOrder( root ) {
			var scope = root.classList && root.classList.contains( 'mw-parser-output' ) ? root : root.querySelector( '.mw-parser-output' );
			if ( ! scope ) { return; }
			var heading = scope.querySelector( 'h2, h3, h4, h5, h6' );
			var infobox = scope.querySelector( '.nv-infobox' );
			if ( ! heading || ! infobox ) { return; }
			var children = Array.prototype.slice.call( scope.children );
			var headingIndex = children.indexOf( heading );
			if ( headingIndex < 0 ) {
				var cursor = heading;
				while ( cursor && cursor.parentNode !== scope ) { cursor = cursor.parentNode; }
				headingIndex = children.indexOf( cursor );
			}
			var infoboxIndex = children.indexOf( infobox );
			if ( infoboxIndex < 0 || headingIndex < 0 || infoboxIndex > headingIndex ) { return; }
			var lead = children.slice( 0, headingIndex ).filter( function ( node ) {
				return node !== infobox && ! node.classList.contains( 'nv-infobox' );
			} );
			var after = lead.length ? lead[ lead.length - 1 ].nextSibling : heading;
			if ( after !== infobox ) { scope.insertBefore( infobox, after ); }
		}

		function sanitizeArticle( root ) {
			var clone = root.cloneNode( true );
			var drop = [
				'.nv-term-card', '.nv-term-definition__link',
				'.nv-term-definition__article', '.toc', '.mw-editsection', '.novark-forum-links',
				'#catlinks', '.catlinks', '.printfooter', '.mw-jump-link', '.mw-cite-backlink'
			];
			drop.forEach( function ( selector ) {
				clone.querySelectorAll( selector ).forEach( function ( node ) { node.remove(); } );
			} );
			clone.querySelectorAll( 'script, iframe, object, embed' ).forEach( function ( node ) { node.remove(); } );
			clone.querySelectorAll( 'a[href*="action=edit"]' ).forEach( function ( node ) { node.remove(); } );
			clone.querySelectorAll( '*' ).forEach( function ( node ) {
				Array.prototype.slice.call( node.attributes || [] ).forEach( function ( attr ) {
					if ( /^on/i.test( attr.name ) ) { node.removeAttribute( attr.name ); }
				} );
			} );
			// 复用原生资料表容器;只有裸表才补一层,避免卡内双重横滚。
			clone.querySelectorAll( 'table' ).forEach( function ( table ) {
				if ( table.closest( '.nv-lock__table' ) ) { return; }
				var existing = table.parentElement;
				if ( existing.classList.contains( 'nv-table-scroll' ) ) {
					existing.classList.add( 'nv-lock__table' );
					return;
				}
				var wrap = document.createElement( 'div' );
				wrap.className = 'nv-lock__table';
				table.parentNode.insertBefore( wrap, table );
				wrap.appendChild( table );
			} );
			clone.querySelectorAll( 'img' ).forEach( function (img ) {
				img.removeAttribute( 'width' );
				img.removeAttribute( 'height' );
				img.loading = 'eager';
				img.decoding = 'async';
			} );
			applyPreviewReadingOrder( clone );
			return clone;
		}

		function fetchArticle( title, section ) {
			var cacheKey = section ? title + '\x1f' + section : title;
			if ( articleCache[ cacheKey ] ) { return Promise.resolve( articleCache[ cacheKey ] ); }
			if ( articleLoading[ cacheKey ] ) { return articleLoading[ cacheKey ]; }
			var request;
			if ( section ) {
				request = new mw.Api().get( {
					action: 'parse', formatversion: 2, page: title, prop: 'sections', redirects: 1
				} ).then( function ( res ) {
					var sections = res && res.parse && res.parse.sections || [];
					var wanted = norm( section );
					var found = sections.filter( function ( sec ) {
						return norm( sec.anchor ) === wanted || norm( sec.line ) === wanted;
					} )[ 0 ];
					return new mw.Api().get( {
						action: 'parse', formatversion: 2, page: title, section: found ? found.index : undefined,
						prop: 'text|revid|modules|modulestyles',
						disableeditsection: 1, disablelimitreport: 1, redirects: 1
					} );
				} );
			} else {
				request = new mw.Api().get( {
					action: 'parse', formatversion: 2, page: title,
					prop: 'text|revid|modules|modulestyles',
					disableeditsection: 1, disablelimitreport: 1, redirects: 1
				} );
			}
			articleLoading[ cacheKey ] = request.then( function ( res ) {
				var text = res && res.parse && res.parse.text;
				if ( ! text ) { throw new Error( 'empty-parse' ); }
				var doc = new DOMParser().parseFromString( '<div>' + text + '</div>', 'text/html' );
				var root = doc.querySelector( '.mw-parser-output' ) || doc.body;
				var preview = sanitizeArticle( root );
				var modules = []
					.concat( ( res.parse.modules || [] ) )
					.concat( ( res.parse.modulestyles || [] ) );
				var externalStyles = [];
				doc.querySelectorAll( 'style' ).forEach( function ( style ) {
					if ( ! root.contains( style ) ) { externalStyles.push( style.textContent || '' ); }
				} );
				articleCache[ cacheKey ] = { content: preview, title: res.parse.title, revid: res.parse.revid, modules: modules, styles: externalStyles };
				delete articleLoading[ cacheKey ];
				return articleCache[ cacheKey ];
			}, function ( err ) {
				delete articleLoading[ cacheKey ];
				throw err;
			} );
			return articleLoading[ cacheKey ];
		}


		function annotateTermLinks( scope, currentId ) {
			scope.querySelectorAll( 'a[href]' ).forEach( function ( a ) {
				var info = infoForTarget( a, currentId, true );
				if ( ! info ) { return; }
				a.classList.add( 'nv-lock__term-link' );
				a.setAttribute( 'data-nv-title', info.term.article || info.term.name );
				if ( info.term.id && info.term.id.indexOf( 'page:' ) !== 0 ) {
					a.setAttribute( 'data-term-id', info.term.id );
				}
			} );
		}
		// 迁移后保留原有“词名识别”:正文纯文本里出现的已知词名/别名也可触发嵌套卡。
		// 只处理段落/列表等正文文本节点;已在链接、表格、标题、脚注里的文字不重复加链。
		function linkifyTerms( scope, currentId ) {
			if ( ! termIndex ) { return; }
			var walker = document.createTreeWalker( scope, NodeFilter.SHOW_TEXT, {
				acceptNode: function ( node ) {
					var parent = node.parentElement;
					if ( ! parent ) { return NodeFilter.FILTER_REJECT; }
					if ( parent.closest( 'a, table, h1, h2, h3, h4, h5, h6, caption, sup, .nv-lock__header' ) ) {
						return NodeFilter.FILTER_REJECT;
					}
					return node.nodeValue && node.nodeValue.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
				}
			} );
			var nodes = [];
			while ( walker.nextNode() ) { nodes.push( walker.currentNode ); }
			nodes.forEach( function ( node ) {
				var text = node.nodeValue;
				var lower = text.toLowerCase();
				var fragment = null;
				var i = 0, textStart = 0;
				while ( i < text.length ) {
					var hit = null, hitKey = '';
					var candidates = termIndex.matchesByInitial[ lower.charAt( i ) ] || [];
					for ( var k = 0; k < candidates.length; k++ ) {
						var candidate = candidates[ k ];
						if ( candidate.term.id !== currentId && lower.startsWith( candidate.key, i ) ) {
							hit = candidate.term;
							hitKey = candidate.key;
							break;
						}
					}
					if ( hit ) {
						if ( !fragment ) { fragment = document.createDocumentFragment(); }
						if ( i > textStart ) { fragment.appendChild( document.createTextNode( text.slice( textStart, i ) ) ); }
						var link = document.createElement( 'a' );
						link.className = 'nv-lock__term-link';
						link.href = termHref( hit );
						link.setAttribute( 'data-term-id', hit.id );
						link.setAttribute( 'title', hit.name );
						link.textContent = text.substr( i, hitKey.length );
						fragment.appendChild( link );
						i += hitKey.length;
						textStart = i;
					} else {
						i++;
					}
				}
				if ( fragment ) {
					if ( textStart < text.length ) { fragment.appendChild( document.createTextNode( text.slice( textStart ) ) ); }
					node.parentNode.replaceChild( fragment, node );
				}
			} );
		}

		function hydrateCard( layer ) {
			var body = layer.el && layer.el.querySelector( '.nv-lock__body' );
			if ( ! body ) { return; }
			var title = articleTitleOf( layer.term );
			var section = layer.term.section || '';
			function insert( entry ) {
				if ( ! layer.el || ! layer.el.isConnected ) { return; }
				var content = entry && entry.content ? entry.content : entry;
				if ( ! content ) { return; }
				body.replaceChildren();
				var article = document.createElement( 'div' );
				article.className = 'nv-lock__article';
				article.setAttribute( 'lang', 'zh-Hans' );
				article.setAttribute( 'dir', 'ltr' );
				article.setAttribute( 'data-preview-mode', 'full' );
				( entry && entry.styles ? entry.styles : [] ).forEach( function ( css ) {
					var style = document.createElement( 'style' );
					style.textContent = css;
					article.appendChild( style );
				} );
				article.appendChild( content.cloneNode( true ) );
				body.appendChild( article );
				scopePreview( article, body, entry.title || title, section );
				annotateTermLinks( article, layer.term.id );
				linkifyTerms( article, layer.term.id );
				fitLayer( layer, article );
				var mods = entry && entry.modules ? entry.modules : [];
				function initModules() {
					try {
						mw.hook( 'wikipage.content' ).fire( window.jQuery ? window.jQuery( article ) : article );
					} catch ( err ) {}
				}
				if ( mods.length && mw.loader && mw.loader.using ) {
					mw.loader.using( mods ).then( initModules, initModules );
				} else {
					initModules();
				}
			}
			fetchArticle( title, section ).then( insert, function () {
				if ( ! layer.el || ! layer.el.isConnected ) { return; }
				body.replaceChildren();
				var error = document.createElement( 'p' );
				error.className = 'nv-lock__error';
				error.textContent = '词条内容暂未读取成功。';
				body.appendChild( error );
			} );
		}


		function samePageHash( target ) {
			var current = ( ( mw.config && mw.config.get( 'wgPageName' ) ) || '' ).replace( /_/g, ' ' );
			return !! ( current && target && target.hash && target.title === current );
		}

		function infoForTarget( a, currentId, insideCard ) {
			if ( ! a || a.classList.contains( 'new' ) ) { return null; }
			if ( ! insideCard && a.closest( '.nv-lock' ) ) { return null; }
			if ( a.closest( '.nv-lock__header' ) || isReference( a ) || isNavigationLink( a ) ) { return null; }
			var target = targetOf( a );
			if ( ! target || samePageHash( target ) ) { return null; }
			if ( ! termIndex ) { return null; }
			var term = null;
			var id = null;
			if ( a.closest( '.nv-term-ref' ) || target.title === '术语库' ) {
				id = ( target.hash.match( /^term-\d+$/ ) || [] )[ 0 ] || null;
			}
			if ( id ) {
				term = termIndex.byId[ id ] || null;
				if ( ! term ) { return null; }
			} else if ( target.hash ) {
				var pageTerm = termIndex.byArticle[ norm( target.title ) ] || termIndex.byTitle[ norm( target.title ) ];
				term = termIndex.bySection[ norm( pageTerm ? pageTerm.article : target.title ) + '#' + norm( target.hash ) ] || null;
				if ( !term && pageTerm && !pageTerm.section ) {
					term = Object.assign( {}, pageTerm, { id: pageTerm.id + '#' + target.hash, section: target.hash, name: pageTerm.name + ' · ' + target.hash } );
				}
				if ( !term ) { return null; }
			} else {
				term = termIndex.byArticle[ norm( target.title ) ] || termIndex.byTitle[ norm( target.title ) ] || null;
				if ( ! term || term.section ) { return null; }
			}
			if ( term ) {
				if ( currentId && term.id === currentId ) { return null; }
				return { id: term.id, term: term };
			}
			return null;
		}

		function termFromAnchor( a ) {
			if ( ! a || ! isBody( a ) || isReference( a ) || a.closest( '.nv-lock' ) ) { return null; }
			return infoForTarget( a, null, false );
		}

		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__loading">正在读取词条…</p></div>';
			var title = card.querySelector( '.nv-lock__title' );
			title.href = termHref( layer.term );
			title.textContent = layer.term.name;
			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 ); } );
			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 = layer.width || 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 = ( layer.width ? Math.min( layer.width, vw - 24 ) : 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 fitLayer( layer, article ) {
			if ( ! layer || ! layer.el ) { return; }
			var vw = window.innerWidth;
			if ( coarse ) {
				layer.width = Math.max( 240, vw - 24 );
				return;
			}
			var hasInfobox = !! article.querySelector( '.nv-infobox, .infobox, .nv-seatmap' );
			var hasTable = !! article.querySelector( 'table' );
			var hasMedia = !! article.querySelector( 'figure, .thumb, .nv-infobox__media, img' );
			var text = ( article.textContent || '' ).replace( /\s+/g, ' ' ).trim();
			var width = hasInfobox || hasTable ? CFG.wideWidth : ( hasMedia ? 500 : 480 );
			if ( ! hasInfobox && ! hasTable && text.length < 180 ) { width = 400; }
			layer.width = Math.max( 320, Math.min( width, vw - 24 ) );
			layer.el.style.width = layer.width + 'px';
			positionLayer( layer );
		}

		function applyVisibility() {
			state.single = coarse;
			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();
			hydrateCard( layer );
			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 openInfoAt( info, depth, sourceLink, anchor, locked ) {
			if ( ! info || ! info.term ) { return; }
			while ( state.stack.length > depth ) {
				var old = state.stack.pop();
				if ( old.raf ) { cancelAnimationFrame( old.raf ); }
				if ( old.el ) { old.el.remove(); }
			}
			createLayer( info.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 );
			}, state.stack[0] && state.stack[0].locked ? CFG.lockedGrace : CFG.grace );
		}
		function scheduleCloseChild( index ) {
			clearTimer( 'closeChildTimer' );
			state.closeChildIndex = index;
			var guarded = state.stack[ index ];
			state.closeChildTimer = setTimeout( function () {
				state.closeChildTimer = 0;
				if ( state.closeChildIndex >= 0 ) { removeFrom( state.closeChildIndex ); }
				state.closeChildIndex = -1;
			}, guarded && guarded.locked ? CFG.lockedGrace : 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 info = infoForTarget( link, layer.term.id, true );
				if ( ! info ) { return; }
				var existing = -1;
				state.stack.forEach( function ( l, i ) { if ( l.term.id === info.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; }
					openInfoAt( info, idx + 1, link, anchorPoint( link ), false );
				}, CFG.childDelay );
				return;
			}
			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 ( to && child.el.contains( to ) ) { return; }
			if ( ! child.locked ) {
				scheduleCloseChild( idx + 1 );
				return;
			}
			if ( to && to.closest( '.nv-lock' ) ) {
				scheduleCloseChild( 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;
			}
			scheduleCloseAll();
		}

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

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

		/* Article links always navigate. Touch preview has its own button. */
        function previewButtons(scope) {
            scope.querySelectorAll('a[href]').forEach(function (a) {
                if (a.nvPreviewButton || !isBody(a) || isReference(a)) { return; }
                var info = infoForTarget(a, null, !!a.closest('.nv-lock'));
                if (!info) { return; }
                var button = document.createElement('button');
                button.type = 'button'; button.className = 'nv-term-preview-trigger';
                button.textContent = '◉'; button.title = '预览';
                button.setAttribute('aria-label', '预览「' + (a.textContent || info.term.name).trim() + '」');
                button.nvTermAnchor = a; a.nvPreviewButton = button;
                a.insertAdjacentElement('afterend', button);
            });
        }
        document.addEventListener('pointerdown', function (e) {
            if (e.pointerType === 'touch') { coarse = true; }
        }, { capture: true, passive: true });
        document.addEventListener('click', function (e) {
            var button = closest(e.target, '.nv-term-preview-trigger');
            if (button && button.nvTermAnchor) {
                var a = button.nvTermAnchor;
                var parent = closest(a, '.nv-lock');
                var layer = parent && state.stack.filter(function (item) { return item.el === parent; })[0];
                var info = infoForTarget(a, layer && layer.term.id, !!parent);
                if (!info) { return; }
                e.preventDefault(); e.stopPropagation();
                if (layer) {
                    var existing = state.stack.findIndex(function (item) { return item.term.id === info.id; });
                    if (existing >= 0) { returnTo(existing); }
                    else { openInfoAt(info, state.stack.indexOf(layer) + 1, a, pointFromLink(a), true); }
                } else { openRoot(info, a, pointFromLink(a), true); }
                return;
            }
            if (state.stack.length && !closest(e.target, '.nv-lock')) { closeAll(false); }
        }, true);
        document.addEventListener('focusin', function (e) {
            if (coarse) { return; }
            var a = closest(e.target, 'a');
            var info = a && termFromAnchor(a);
            if (info) { openRoot(info, a, pointFromLink(a), true); }
        });
        mw.hook('wikipage.content').add(function (content) {
            var scope = content && content.jquery ? content[0] : content;
            if (scope && scope.querySelectorAll && termIndex) { previewButtons(scope); }
        });

		function onKeydown( e ) {
			if ( e.key === 'Escape' && state.stack.length ) {
				e.preventDefault();
				closeAll( false );
			}
		}
		document.addEventListener( 'keydown', onKeydown, true );

		/* ---- boot ---- */
		fetchTerms().then( function () { previewButtons( document ); } ).catch( function () {} );
		window.NvLock = {
			version: '2.3.0-page-terms',
			termCount: function () { return termIndex ? termIndex.raw.terms.length : -1; },
			debugLink: function ( el ) { return { body: isBody( el ), target: targetOf( el ), ref: isReference( el ), nav: isNavigationLink( el ), info: infoForTarget( el, null, false ) }; },
			debugInfo: function ( title ) { return { index: !! termIndex, byTitle: !!( termIndex && termIndex.byTitle[ norm( title ) ] ), bySection: !!( termIndex && termIndex.bySection[ norm( title ) ] ) }; },
			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', 'mediawiki.api' ] ).then( function () {
			if ( document.readyState === 'loading' ) { document.addEventListener( 'DOMContentLoaded', boot ); }
			else { boot(); }
		} );
	} else if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', boot );
	} else {
		boot();
	}
} )();

/* Source: table-layout.js */
/* Shared table behaviour: wrap long description columns without intercepting input. */
( function () {
	'use strict';

	function markWrappingTables( scope ) {
		Array.prototype.forEach.call(
			scope.querySelectorAll( '.nv-table-scroll table' ),
			function ( table ) {
				if ( table.dataset.nvWrapChecked === '1' ) { return; }
				table.dataset.nvWrapChecked = '1';
				var firstRow = ( table.tHead && table.tHead.rows[ 0 ] ) || table.rows[ 0 ];
				if ( ! firstRow ) { return; }
				var headerText = ( firstRow.textContent || '' ).replace( /\s+/g, '' );
				var cols = Array.prototype.reduce.call( firstRow.cells, function ( n, cell ) { return n + ( cell.colSpan || 1 ); }, 0 );
				if ( cols > 5 || !/(描述|说明|备注)/.test( headerText ) ) { return; }
				var longText = Array.prototype.some.call( table.querySelectorAll( 'td' ), function ( cell ) {
					return ( cell.textContent || '' ).trim().length > 60;
				} );
				if ( ! longText ) { return; }
				table.classList.add( 'nv-table--wrap' );
				var wrap = table.closest( '.nv-table-scroll' );
				if ( wrap ) { wrap.classList.add( 'nv-table-scroll--wrap' ); }
			}
		);
	}

	mw.hook( 'wikipage.content' ).add( function ( $content ) {
		$content.each( function () { markWrappingTables( this ); } );
	} );
}() );

/* Source: page-footer.js */
/* Page footer: references, term maintenance and discussion links. */
( function () {
	'use strict';
	if ( !window.mw || !mw.config ) { return; }
	var action = mw.config.get( 'wgAction' );
	if ( action !== 'view' || mw.config.get( 'wgNamespaceNumber' ) !== 0 ||
		mw.config.get( 'wgDiffNewId' ) !== null ) { return; }
	var pageTitle = ( mw.config.get( 'wgPageName' ) || '' ).replace( /_/g, ' ' );
	if ( !pageTitle || pageTitle === '首页' || pageTitle === '术语库' || pageTitle === '术语库/编辑' ) { return; }
	var norm = function ( s ) { return String( s || '' ).replace( /_/g, ' ' ).replace( /\s+/g, ' ' ).trim().toLowerCase(); };
	var openMenu = null;

	function closeMenu() {
		if ( openMenu ) {
			openMenu.parentNode.querySelector( '[aria-expanded]' ).setAttribute( 'aria-expanded', 'false' );
			openMenu.remove();
			openMenu = null;
		}
	}

	function positionMenu( menu, button ) {
		var margin = 12, vw = window.innerWidth, vh = window.innerHeight;
		menu.style.width = Math.min( 320, vw - margin * 2 ) + 'px';
		menu.style.maxHeight = Math.min( 304, vh - margin * 2 ) + 'px';
		var br = button.getBoundingClientRect();
		var rect = menu.getBoundingClientRect();
		var left = Math.max( margin, Math.min( br.left, vw - margin - rect.width ) );
		var below = vh - br.bottom - margin;
		var above = br.top - margin;
		var top = ( below >= Math.min( rect.height, 220 ) || below >= above ) ? br.bottom + 6 : br.top - 6 - rect.height;
		top = Math.max( margin, Math.min( top, vh - margin - rect.height ) );
		menu.style.left = Math.round( left ) + 'px';
		menu.style.top = Math.round( top ) + 'px';
	}

	function makeLink( label, href ) {
		var a = document.createElement( 'a' );
		a.className = 'nv-page-footer__item';
		a.href = href;
		a.textContent = label;
		return a;
	}

	function makeCopyButton( label, value ) {
		var button = document.createElement( 'button' );
		button.type = 'button';
		button.className = 'nv-page-footer__item';
		button.textContent = label;
		button.setAttribute( 'data-label', label );
		button.addEventListener( 'click', function () { window.nvCopyText( value, button ); } );
		return button;
	}

	function makeMenuButton( label, items ) {
		var wrap = document.createElement( 'span' );
		wrap.className = 'nv-page-footer__menu-wrap';
		var button = document.createElement( 'button' );
		button.type = 'button';
		button.className = 'nv-page-footer__item';
		button.textContent = label;
		button.setAttribute( 'data-label', label );
		button.setAttribute( 'aria-haspopup', 'menu' );
		button.setAttribute( 'aria-expanded', 'false' );
		button.addEventListener( 'click', function ( e ) {
			e.stopPropagation();
			if ( openMenu && openMenu.parentNode === wrap ) { closeMenu(); return; }
			closeMenu();
			var menu = document.createElement( 'div' );
			menu.className = 'nv-footer-menu';
			menu.setAttribute( 'role', 'menu' );
			items.forEach( function ( item ) {
				var row = document.createElement( 'button' );
				row.type = 'button';
				row.className = 'nv-footer-menu__item';
				row.textContent = item.label;
				row.addEventListener( 'click', function () {
					closeMenu();
					if ( item.href ) { location.href = item.href; }
					else { window.nvCopyText( item.value, button ); }
				} );
				menu.appendChild( row );
			} );
			wrap.appendChild( menu );
			openMenu = menu;
			button.setAttribute( 'aria-expanded', 'true' );
			positionMenu( menu, button );
			var first = menu.querySelector( '.nv-footer-menu__item' );
			if ( first ) { first.focus( { preventScroll: true } ); }
		} );
		wrap.addEventListener( 'keydown', function ( e ) {
			if ( e.key === 'Escape' ) { closeMenu(); button.focus(); }
		} );
		wrap.appendChild( button );
		return wrap;
	}

	function currentSections() {
		var content = document.querySelector( '#mw-content-text .mw-parser-output' );
		if ( ! content ) { return []; }
		var out = [];
		content.querySelectorAll( 'h2, h3, h4, h5, h6' ).forEach( function ( heading ) {
			if ( heading.closest( '.nv-lock' ) ) { return; }
			var headline = heading.querySelector( '.mw-headline' );
			var anchor = heading.id || ( headline && headline.id );
			if ( ! anchor ) { return; }
			var label = ( headline ? headline.textContent : heading.textContent ).trim();
			if ( ! label ) { return; }
			var panel = heading.closest( '.tabber__panel' );
			if ( panel ) {
				var tab = document.getElementById( panel.getAttribute( 'aria-labelledby' ) );
				if ( tab ) { label = tab.textContent.trim() + ' · ' + label; }
			}
			out.push( { anchor: anchor, label: label } );
		} );
		return out;
	}

	function nativeRef( term ) {
		var title = term.article || term.name;
		var target = title;
		if ( term.section ) { target += '#' + term.section; }
		if ( ! term.section && norm( title ) === norm( term.name ) ) { return '[[' + title + ']]'; }
		return '[[' + target + '|' + term.name + ']]';
	}

	function removeSeparators( container ) {
		if ( ! container ) { return; }
		container.querySelectorAll( ':scope > .nv-page-footer__sep' ).forEach( function ( node ) { node.remove(); } );
	}

	function addSeparators( container ) {
		if ( ! container ) { return; }
		removeSeparators( container );
		var items = Array.prototype.slice.call( container.children ).filter( function ( node ) {
			return ! node.classList.contains( 'nv-page-footer__sep' ) && ! node.classList.contains( 'nv-copy-fallback' );
		} );
		items.forEach( function ( item, index ) {
			if ( index === 0 ) { return; }
			var separator = document.createElement( 'span' );
			separator.className = 'nv-page-footer__sep';
			separator.setAttribute( 'aria-hidden', 'true' );
			separator.textContent = '|';
			container.insertBefore( separator, item );
		} );
	}

	function row( label ) {
		var line = document.createElement( 'div' );
		line.className = 'nv-page-footer__row';
		var name = document.createElement( 'span' );
		name.className = 'nv-page-footer__label';
		name.textContent = label;
		var items = document.createElement( 'span' );
		items.className = 'nv-page-footer__items';
		line.appendChild( name );
		line.appendChild( items );
		return { line: line, items: items };
	}

	function pageFooterShell() {
		var existing = document.getElementById( 'nv-page-footer' );
		if ( existing ) { return existing; }
		var footer = document.createElement( 'div' );
		footer.id = 'nv-page-footer';
		footer.className = 'nv-page-footer';
		var help = row( '帮助:' );
		footer.appendChild( help.line );
		footer._help = help.items;
		var catlinks = document.getElementById( 'catlinks' );
		if ( catlinks && catlinks.parentNode ) {
			catlinks.parentNode.insertBefore( footer, catlinks.nextSibling );
		} else {
			var content = document.querySelector( '#mw-content-text' );
			if ( content ) { content.appendChild( footer ); }
		}
		document.addEventListener( 'click', function ( e ) {
			if ( openMenu && ! openMenu.contains( e.target ) && ! e.target.closest( '.nv-page-footer__menu-wrap' ) ) { closeMenu(); }
		}, true );
		return footer;
	}

	function loadTerms() {
		return window.nvTermCatalog().then( function ( data ) { return data.terms || []; } );
	}

	function addHelp( footer, terms ) {
		var target = footer._help;
		var pageLevel = terms.filter( function ( term ) {
			return ! term.section && norm( term.article || term.name ) === norm( pageTitle );
		} )[ 0 ] || null;
		var sections = terms.filter( function ( term ) {
			return term.section && norm( term.article ) === norm( pageTitle );
		} );
		if ( pageLevel && pageLevel.curated ) {
			target.appendChild( makeCopyButton( '复制术语引用', nativeRef( pageLevel ) ) );
			target.appendChild( makeLink( '维护术语', mw.util.getUrl( '术语库/编辑', { term: pageLevel.id } ) ) );
		} else if ( sections.length === 1 ) {
			target.appendChild( makeCopyButton( '复制术语引用', nativeRef( sections[ 0 ] ) ) );
			target.appendChild( makeLink( '维护术语', mw.util.getUrl( '术语库/编辑', { term: sections[ 0 ].id } ) ) );
		} else if ( sections.length > 1 ) {
			target.appendChild( makeMenuButton( '复制术语引用', sections.map( function ( term ) {
				return { label: term.name, value: nativeRef( term ) };
			} ) ) );
		} else {
			var list = currentSections();
			target.appendChild( makeMenuButton( '复制引用', [ { label: '整页', value: '[[' + pageTitle + ']]' } ].concat( list.map( function ( section ) {
				return { label: section.label, value: '[[' + pageTitle + '#' + section.anchor + '|' + section.label + ']]' };
			} ) ) ) );
			if ( pageLevel ) {
				target.appendChild( makeLink( '编辑词条', mw.util.getUrl( pageTitle, { action: 'edit' } ) ) );
				target.appendChild( makeMenuButton( '别名与章节', [ { label: '整页别名', href: mw.util.getUrl( '术语库/编辑', { name: pageTitle, article: pageTitle } ) } ].concat( list.map( function ( section ) {
				return { label: section.label, href: mw.util.getUrl( '术语库/编辑', { name: section.label, article: pageTitle, section: section.anchor } ) };
				} ) ) ) );
			}
		}
		target.appendChild( makeLink( '历史', mw.util.getUrl( 'Special:History/' + pageTitle ) ) );
		target.appendChild( makeLink( '链入页面', mw.util.getUrl( 'Special:WhatLinksHere/' + pageTitle ) ) );
		addSeparators( target );
	}


	function start() {
		var footer = pageFooterShell();
		loadTerms().then( function ( terms ) { addHelp( footer, terms ); } ).catch( function () { if ( !footer._help.childElementCount ) { addHelp( footer, [] ); } } );
	}
	if ( document.readyState === 'loading' ) { document.addEventListener( 'DOMContentLoaded', start, { once: true } ); }
	else { start(); }
}() );

/* Source: page-status.js */
/* ==========================================================================
   Page status banners: read the page's categories and render framed
   status banners at the top of the article. The
   templates only categorise; the visual layer lives here and in
   Template:状态/styles.css.
   ========================================================================== */
( function () {
	'use strict';

	var STATUS = {
		'剧透': { icon: 'spoiler', tone: 'spoiler', title: '剧透', text: '此页面包含剧透内容,可能涉及尚未公开的跑团剧情、角色结局或重要谜底,请谨慎阅读。' },
		'非正史': { icon: 'noncanon', tone: 'noncanon', title: '非正史', text: '当前页面属于非正史内容,可作为衍生创作参考,但不自动进入主设定。' },
		'跑团记录': { icon: 'campaign', tone: 'campaign', title: '跑团记录', text: '当前页面为跑团记录,内容首先属于对应战役的推演记录;若需进入主设定,应另行经过引入流程。' },
		'消歧义': { icon: 'disambiguation', tone: 'disambiguation', title: '消歧义', text: '当前页面是消歧义页,用于罗列标题相同或相近、但内容不同的条目。' },
		'修订中': { icon: 'revising', tone: 'revising', title: '修订中', text: '当前页面正在修订,内容可能继续调整。' },
		'确认中': { icon: 'confirming', tone: 'confirming', title: '确认中', text: '当前页面的内容正在讨论或核对,相关结论尚待确认。' },
		'已锚定': { icon: 'anchored', tone: 'anchored', title: '已锚定', text: '当前页面所描述的设定已被锚定,可以自由参考和引用;修改事实性内容前,请先依照共创指南发起讨论。' },
		'需要改进': { icon: 'improve', tone: 'improve', title: '需要改进', text: '当前页面仍需改进,欢迎补充内容、修改措辞和完善链接。' },
		'精选': { icon: 'featured', tone: 'featured', title: '精选', text: '此页面被标记为精选内容,可作为同类条目的高质量参考。' }
	};

	var STATUS_ORDER = [ '剧透', '非正史', '跑团记录', '确认中', '修订中', '需要改进', '已锚定', '精选', '消歧义' ];

	function sourceFor( content, kind, type ) {
		var nodes = content.querySelectorAll( '.nv-status-source' );
		for ( var i = 0; i < nodes.length; i++ ) {
			if ( nodes[ i ].getAttribute( 'data-nv-kind' ) === kind &&
				nodes[ i ].getAttribute( 'data-nv-type' ) === type ) {
				return nodes[ i ];
			}
		}
		return null;
	}

	function appendSource( body, source ) {
		if ( !source ) { return; }
		[ 'note', 'discuss' ].forEach( function ( suffix ) {
			var sourceEl = source.querySelector( '.nv-status-' + suffix );
			if ( !sourceEl ) { return; }
			var box = document.createElement( 'div' );
			box.className = 'nv-status-banner__' + suffix;
			Array.prototype.forEach.call( sourceEl.childNodes, function ( node ) { box.appendChild( node.cloneNode( true ) ); } );
			if ( box.textContent.trim() || box.querySelector( 'a' ) ) {
				body.appendChild( box );
			}
		} );
	}

	function makeBanner( def, source ) {
		var banner = document.createElement( 'div' );
		banner.className = 'nv-status-banner nv-status-banner--' + def.tone;
		var icon = document.createElement( 'span' );
		icon.className = 'nv-status-banner__icon nv-icon nv-icon--' + def.icon;
		icon.setAttribute( 'aria-hidden', 'true' );
		var body = document.createElement( 'div' );
		body.className = 'nv-status-banner__body';
		var title = document.createElement( 'strong' );
		title.className = 'nv-status-banner__title';
		title.textContent = def.title;
		body.appendChild( title );
		if ( def.text ) {
			var text = document.createElement( 'span' );
			text.className = 'nv-status-banner__text';
			text.textContent = def.text;
			body.appendChild( text );
		}
		appendSource( body, source );
		banner.appendChild( icon );
		banner.appendChild( body );
		return banner;
	}

	function render( $content ) {
		if ( !document.body || !document.body.classList.contains( 'action-view' ) ) { return; }
		if ( !window.mw || !mw.config || mw.config.get( 'wgNamespaceNumber' ) !== 0 ||
			mw.config.get( 'wgDiffNewId' ) !== null ) { return; }
		var content = document.querySelector( '#mw-content-text .mw-parser-output' );
		if ( !content || !$content.toArray().some( function ( root ) { return root === content || root.contains( content ); } ) ) { return; }
		var old = content.querySelector( '[data-nv-status-banner]' );
		var cats = mw.config.get( 'wgCategories' ) || [];
		var signature = JSON.stringify( cats );
		if ( old && old.getAttribute( 'data-nv-categories' ) === signature ) { return; }
		if ( old ) { old.remove(); }
		var nodes = [];
		var i;
		for ( i = 0; i < STATUS_ORDER.length; i++ ) {
			if ( cats.indexOf( STATUS_ORDER[ i ] ) !== -1 ) {
				nodes.push( makeBanner( STATUS[ STATUS_ORDER[ i ] ], sourceFor( content, 'status', STATUS_ORDER[ i ] ) ) );
				break;
			}
		}
		if ( !nodes.length ) { return; }

		var stack = document.createElement( 'div' );
		stack.className = 'nv-status-stack';
		stack.setAttribute( 'data-nv-status-banner', '' );
		stack.setAttribute( 'data-nv-categories', signature );
		nodes.forEach( function ( node ) { stack.appendChild( node ); } );
		content.insertBefore( stack, content.firstChild );
	}

	mw.hook( 'wikipage.content' ).add( render );
}() );