跳到正文
Novark

MediaWiki:Common.js:修订间差异

Phase1EmergencyAdmin
Phase1EmergencyAdmin​(留言 | 贡献) (正文术语统一:保留已有登记分类标签的目录作用,与原生分类合并去重)
Phase1EmergencyAdmin
Phase1EmergencyAdmin​(留言 | 贡献) (AI辅助:删除页尾重复讨论行,保留原生顶部讨论入口)
小
 
(未显示2个用户的8个中间版本)
第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 buildSpellUI() {
 
     var host = document.getElementById('spell-filter-host');
   function spellSelect(id, labelText, values, optionLabel) {
     var table = document.querySelector('.mien-spell-table');
     var select = el('select', { id: id, 'aria-label': labelText });
     if (!host || !table || host.dataset.built === 'true') return;
     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.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 spellRows(table) {
     function applyFilters() {
     return Array.prototype.slice.call(table.querySelectorAll('tbody tr')).filter(function (row) { return row.cells && row.cells[0] && row.cells[0].tagName === 'TD'; });
      var query = search.value.trim().toLowerCase();
  }
      rows.forEach(function (row) {
  function cellText(row, index) {
        var matches = (!query || row.searchText.indexOf(query) !== -1) &&
    var cell = row.cells && row.cells[index];
          (!classFilter.value || row.className.indexOf(classFilter.value) !== -1) &&
    return cell ? cell.textContent.trim() : '';
          (!levelFilter.value || row.level === levelFilter.value) &&
  }
          (!schoolFilter.value || row.school === schoolFilter.value) &&
  function applySpellFilters(table) {
          (!domainFilter.value || row.domain === domainFilter.value);
    var search = document.getElementById('spell-search');
        row.element.hidden = !matches;
    var classFilter = document.getElementById('spell-class-filter');
        row.element.classList.toggle('mien-spell-row-hidden', !matches);
    var levelFilter = document.getElementById('spell-level-filter');
    var schoolFilter = document.getElementById('spell-school-filter');
    var domainFilter = document.getElementById('spell-domain-filter');
    var searchValue = (search && search.value || '').trim().toLowerCase();
    var classValue = classFilter && classFilter.value || '';
    var levelValue = levelFilter && levelFilter.value || '';
    var schoolValue = schoolFilter && schoolFilter.value || '';
    var domainValue = domainFilter && domainFilter.value || '';
    spellRows(table).forEach(function (row) {
      var cells = Array.prototype.map.call(row.cells, function (cell) { return cell.textContent.trim(); });
      var rowClass = spellNoValue(cellText(row, 3));
      var rowLevel = cellText(row, 1).replace(/\s*级$/, '').trim();
      var rowSchool = cellText(row, 2);
      var rowDomain = cellText(row, 4);
      var matches = (!searchValue || cells.join(' ').toLowerCase().indexOf(searchValue) !== -1) &&
        (!classValue || rowClass.indexOf(classValue) !== -1) &&
        (!levelValue || rowLevel === levelValue) &&
        (!schoolValue || rowSchool === schoolValue) &&
        (!domainValue || (domainValue === '—' ? (rowDomain === '—' || rowDomain === '-' || rowDomain === '') : rowDomain === domainValue));
      row.hidden = !matches;
      row.classList.toggle('mien-spell-row-hidden', !matches);
    });
  }
  function sortSpellTable(table, headerIndex, ascending) {
    var tbody = table.tBodies[0];
    if (!tbody) return;
    var headRow = (table.tHead && table.tHead.rows[0]) || table.rows[0];
    var header = headRow ? headRow.cells[headerIndex] : null;
    var numeric = header ? header.textContent.indexOf('等级') !== -1 : false;
    spellRows(table).sort(function (a, b) {
      var av = cellText(a, headerIndex), bv = cellText(b, headerIndex);
      var cmp = numeric ? num(av.replace(/\s*级$/, ''), 0) - num(bv.replace(/\s*级$/, ''), 0) : av.localeCompare(bv, 'zh-Hans-CN');
      return ascending ? cmp : -cmp;
    }).forEach(function (row) { tbody.appendChild(row); });
    applySpellFilters(table);
  }
  function bindSpellTable() {
    var table = document.querySelector('.mien-spell-table');
    if (!table || table.dataset.mienSpellInitialized === 'true') return;
    table.dataset.mienSpellInitialized = 'true';
    ['spell-search', 'spell-class-filter', 'spell-level-filter', 'spell-school-filter', 'spell-domain-filter'].forEach(function (id) {
      var control = document.getElementById(id);
      if (!control) return;
      control.addEventListener('input', function () { applySpellFilters(table); });
      control.addEventListener('change', function () { applySpellFilters(table); });
    });
    var clear = document.getElementById('spell-clear');
    if (clear) clear.addEventListener('click', function () {
      ['spell-search', 'spell-class-filter', 'spell-level-filter', 'spell-school-filter', 'spell-domain-filter'].forEach(function (id) {
        var control = document.getElementById(id);
        if (control) control.value = '';
      });
      applySpellFilters(table);
    });
    var headRow = (table.tHead && table.tHead.rows[0]) || table.rows[0];
    if (headRow) {
      Array.prototype.forEach.call(headRow.cells, function (th, index) {
        th.style.cursor = 'pointer';
        th.title = '点击按此列排序';
        th.addEventListener('click', function () {
          var ascending = th.getAttribute('data-sort-direction') !== 'asc';
          Array.prototype.forEach.call(headRow.cells, function (h) { h.removeAttribute('data-sort-direction'); });
          th.setAttribute('data-sort-direction', ascending ? 'asc' : 'desc');
          sortSpellTable(table, index, ascending);
        });
       });
       });
     }
     }
    applySpellFilters(table);
  }


  function init() {
    bindControls(controls, applyFilters);
     if (document.getElementById('mien-price-calculator') || document.getElementById('mien-credit-currency-calculator')) {
    clear.addEventListener('click', function () {
       var economy = readEconomyData();
      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 (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
/* Shared clipboard action for the page footer and glossary editor. */
  ---------------------------------------------------------------------------
window.nvCopyText = function (value, button) {
  相对 v1 的改动(对应 03 审阅修正点,详见《全局设计规范-v2.md》§7):
  var old = button.getAttribute('data-label') || button.textContent;
  03-1 站上无 Gadgets:本文件放 MediaWiki:Common.js;用 mw.loader.using
  function done() {
        等 mediawiki.user / mediawiki.util 就绪后再初始化。
    button.textContent = '已复制';
  03-2 搜索:生产 Citizen 搜索是原生 form,无动态结果浮层;本文件不再维护
    window.setTimeout(function () { button.textContent = old; }, 1200);
        第二套搜索面板,回车/按钮走 MediaWiki 原生搜索页。
  }
  03-3 导航等待仅限 body.action-view 阅读页;click 与 submit 同等排除
  function fallback() {
        OOUI、PageForms、术语编辑器;编辑/预览/保存/特殊页不显示等待线。
    var area = document.createElement('textarea');
  03-4 空页/搜索无结果只用生产静态几何,不在 JS 再造 SVG。
    area.value = value;
  03-6 theme-color 切换后读取 body 计算样式回写,单一颜色来源;
    area.setAttribute('readonly', '');
        html class 观察做字符串去抖。
    area.style.position = 'fixed';
  已核实并内置:主题类 skin-theme-clientpref-{day|night|os}、
    area.style.left = '-9999px';
  浮动标题 #citizen-sticky-header;搜索走原生 MediaWiki 表单。
    document.body.appendChild(area);
  语法 ES2017。
    area.select();
  ========================================================================== */
    var copied = false;
( function () {
    try { copied = document.execCommand('copy'); } catch (err) { copied = false; }
'use strict';
    document.body.removeChild(area);
 
    if (copied) { done(); return; }
function init() {
    var input = button.parentNode && button.parentNode.querySelector('.nv-copy-fallback');
var CFG = Object.assign( {
    if (input) { input.remove(); }
themePrefKey: 'skin-theme',
    input = document.createElement('input');
themeValues: { day: 'day', night: 'night', os: 'os' },
    input.className = 'nv-copy-fallback';
 
    input.readOnly = true;
/* 已核实的 DOM */
    input.value = value;
stickyHeader: '#citizen-sticky-header',
    input.setAttribute('aria-label', '复制失败,请手动选择文字');
 
    if (button.parentNode) { button.parentNode.insertBefore(input, button.nextSibling); }
/* 日夜按钮挂载:二选一。mw-portlet-personal 在生产 DOM 存在;
    input.focus();
  具体放哪由 DS 定,两项都空则不显示按钮(API 仍可调用) */
    input.select();
themeToggleMount: null,
    button.textContent = '请手动复制';
themeTogglePortlet: 'p-personal',
    window.setTimeout(function () { if (input.isConnected) { input.remove(); } button.textContent = old; }, 12000);
themeToggleCompact: true,
  }
 
  if (navigator.clipboard && navigator.clipboard.writeText && window.isSecureContext) {
navPendingDelay: 120,
    navigator.clipboard.writeText(value).then(done, fallback);
navPendingTimeout: 8000
  } else {
}, window.MienInteractionConfig || {} );
    fallback();
 
  }
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. 日夜切换 ==================== */
/* Source: term-catalog.js */
function prefs() {
/* Shared cached loader for the term JSON index (read-only consumers: NvLock preview
return ( window.mw && mw.user && mw.user.clientPrefs ) ? mw.user.clientPrefs : null;
  and the unified page footer). The editor keeps its own uncached fetch to read the
}
  latest revision + basetimestamp for conflict-safe saves. */
function currentPref() {
window.nvTermData = ( function () {
var cp = prefs();
var cached = null, loading = null;
if ( cp && typeof cp.get === 'function' ) {
return function () {
try { var v = cp.get( CFG.themePrefKey ); if ( v ) { return v; } } catch ( e ) {}
if ( cached ) { return Promise.resolve( cached ); }
}
if ( loading ) { return loading; }
var m = html.className.match( new RegExp( '(?:^|\\s)' + esc( CFG.themePrefKey ) + '-clientpref-(\\S+)' ) );
var url = mw.util.getUrl( 'Module:术语库/data.json', { action: 'raw' } );
return m ? m[ 1 ] : null;
loading = fetch( url, { credentials: 'same-origin' } ).then( function ( r ) {
}
if ( !r.ok ) { throw new Error( 'terms-' + r.status ); }
function isNight() {
return r.json();
var p = currentPref();
} ).then( function ( data ) {
if ( p === CFG.themeValues.night ) { return true; }
cached = data;
if ( p === CFG.themeValues.day ) { return false; }
loading = null;
return !!( window.matchMedia && window.matchMedia( '(prefers-color-scheme: dark)' ).matches );
return data;
}
} ).catch( function ( err ) {
function syncThemeUi() {
loading = null;
var night = isNight();
throw err;
qsa( '.mien-theme-toggle' ).forEach( function ( b ) {
} );
b.setAttribute( 'aria-pressed', night ? 'true' : 'false' );
return loading;
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 ); }
}
}
/* Citizen 的 clientPrefs polyfill 使用 localStorage 键 mwclientpreferences,
  且仅在原生外观面板按需加载后覆盖;直接调用 MW 核心 clientPrefs 只写 cookie,
  匿名用户刷新后会丢主题。这里同步写入同一份存储,保持单一偏好来源。 */
function saveThemePref( value ) {
var feature = CFG.themePrefKey;
try {
var classRe = new RegExp( '(^|\\s)' + esc( feature ) + '-clientpref-[a-zA-Z0-9]+(?=\\s|$)', 'g' );
html.className = html.className.replace( classRe, ' ' ).replace( /\\s+/g, ' ' ).trim();
} catch ( e ) {}
html.classList.add( feature + '-clientpref-' + value );
try {
var storage = ( window.mw && mw.storage ) ? mw.storage : {
get: function ( key ) { try { return window.localStorage.getItem( key ); } catch ( e ) { return null; } },
set: function ( key, val ) { try { window.localStorage.setItem( key, val ); } catch ( e ) {} }
};
var data = {};
String( storage.get( 'mwclientpreferences' ) || '' ).split( ',' ).forEach( function ( pair ) {
var m = /^([\\w-]+)-clientpref-([\\w]+)$/.exec( pair );
if ( m ) { data[ m[ 1 ] ] = m[ 2 ]; }
} );
data[ feature ] = value;
var parts = [];
Object.keys( data ).forEach( function ( key ) { parts.push( key + '-clientpref-' + data[ key ] ); } );
storage.set( 'mwclientpreferences', parts.join( ',' ) );
} catch ( e ) {}
}
function setTheme( value ) {
var cp = prefs();
if ( !cp || typeof cp.set !== 'function' ) { return false; }
var apply = function () { try { cp.set( CFG.themePrefKey, value ); } catch ( e ) {} saveThemePref( 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) ==================== */
/* Page-backed terms. Native pages/categories/redirects are the catalogue; the
var pendingTimer = 0, pendingGuard = 0;
  existing JSON supplies compatible IDs, explicit aliases and section entries. */
function clearPending() {
window.nvTermCatalog = ( function () {
clearTimeout( pendingTimer ); clearTimeout( pendingGuard );
'use strict';
html.classList.remove( 'mien-nav-pending' );
var cached, loading, loadedAt = 0;
}
var excluded = new Set( [ '索引页面', '站点导航', '帮助与指南' ] );
function showPending() {
var maintenance = new Set( [ '术语', '资料', '已锚定', '需要改进', '待改进', '剧透' ] );
html.classList.add( 'mien-nav-pending' );
function norm( value ) { return String( value || '' ).replace( /_/g, ' ' ).trim().toLowerCase(); }
clearTimeout( pendingGuard );
function readPages( force ) {
pendingGuard = setTimeout( clearPending, CFG.navPendingTimeout );
var pages = new Map(), api = new mw.Api();
}
function read( continuation ) {
/* click 与 submit 共用的排除区(03-3:两者同等排除) */
return api.get( Object.assign( {
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';
action: 'query', formatversion: 2, generator: 'allpages', gapnamespace: 0,
function willNavigateSameTab( e, a ) {
// Native browser caching also covers navigation between articles.
if ( e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey ) { return false; }
maxage: force ? 0 : 60,
if ( a.target && a.target !== '_self' ) { return false; }
gapfilterredir: 'nonredirects', gaplimit: 'max',
if ( a.hasAttribute( 'download' ) || a.getAttribute( 'role' ) === 'button' ) { return false; }
prop: 'info|categories|redirects|pageprops', inprop: 'url',
if ( a.closest( EXCLUDE_ZONE ) ) { return false; }
cllimit: 'max', rdlimit: 'max', rdnamespace: 0, rdprop: 'title|fragment',
var raw = a.getAttribute( 'href' ) || '';
ppprop: 'disambiguation'
if ( !raw || raw.charAt( 0 ) === '#' || /^(javascript|mailto|tel):/i.test( raw ) ) { return false; }
}, continuation || {} ) ).then( function ( result ) {
var u;
( result.query && result.query.pages || [] ).forEach( function ( page ) {
try { u = new URL( a.href, location.href ); } catch ( err ) { return false; }
var old = pages.get( page.pageid );
if ( u.origin !== location.origin ) { return false; }
if ( old ) {
if ( u.pathname === location.pathname && u.search === location.search ) { return false; }
page.categories = ( old.categories || [] ).concat( page.categories || [] );
/* 去往编辑/提交动作的链接不显示等待线(点红链直达编辑器属原生行为) */
page.redirects = ( old.redirects || [] ).concat( page.redirects || [] );
if ( /[?&]action=(edit|submit|formedit)\b/.test( u.search ) ) { return false; }
}
return true;
pages.set( page.pageid, page );
}
} );
if ( isReadingPage ) {
return result.continue ? read( result.continue ) : Array.from( pages.values() );
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 );
return read();
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 } );
}
}
 
function combine( pages, metadata ) {
/* 03-1:等依赖就绪再初始化(Common.js 环境必有 mw.loader) */
var terms = [], targets = Object.create( null ), order = ( metadata.categoryOrder || [] ).slice();
if ( window.mw && mw.loader && mw.loader.using ) {
pages.forEach( function ( page ) {
mw.loader.using( [ 'mediawiki.user', 'mediawiki.util', 'mediawiki.storage' ] ).then( function () {
var categories = Array.from( new Set( ( page.categories || [] ).map( function ( cat ) {
if ( document.readyState === 'loading' ) {
return cat.title.replace( /^(Category|分类):/, '' );
document.addEventListener( 'DOMContentLoaded', init );
} ) ) );
} else {
if ( page.missing || page.ns !== 0 || !page.length || page.pageprops &&
init();
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; } );
} );
} );
} else if ( document.readyState === 'loading' ) {
( metadata.terms || [] ).forEach( function ( record ) {
document.addEventListener( 'DOMContentLoaded', init ); /* 本地演示用回退 */
var page = targets[ norm( record.article || record.name ) ];
} else {
if ( !page ) { return; }
init();
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;
};
}() );
}() );


/* Shared clipboard action for the page footer and glossary editor. */
/* Source: term-preview.js */
window.nvCopyText = function (value, button) {
/* ==========================================================================
  var old = button.getAttribute('data-label') || button.textContent;
  Term preview: progressive reading chains backed by canonical page content.
  function done() {
  - 真实 800ms 进度;满圈才 locked,可移入
    button.textContent = '已复制';
  - 根词 180ms 延迟;未满圈离开立即取消
    window.setTimeout(function () { button.textContent = old; }, 1200);
  - 每层以当次触发鼠标坐标为锚,不排队;卡片内容按规范词条正文加载(有界卡内可读)
  }
  - 无深度上限;窄屏单面板可继续深入
  function fallback() {
  ========================================================================== */
    var area = document.createElement('textarea');
( function () {
    area.value = value;
'use strict';
    area.setAttribute('readonly', '');
// Previews belong to reading pages, not navigation or revision tools.
    area.style.position = 'fixed';
if ( mw.config.get( 'wgIsMainPage' ) || mw.config.get( 'wgAction' ) !== 'view' ||
    area.style.left = '-9999px';
mw.config.get( 'wgDiffNewId' ) !== null || mw.config.get( 'wgNamespaceNumber' ) < 0 ) { return; }
    document.body.appendChild(area);
 
    area.select();
function boot() {
    var copied = false;
if ( window.NvLock || !document.querySelector( '#mw-content-text .mw-parser-output' ) ) { return; }
    try { copied = document.execCommand('copy'); } catch (err) { copied = false; }
 
    document.body.removeChild(area);
var CFG = {
    if (copied) { done(); return; }
rootDelay: 180,
    var input = button.parentNode && button.parentNode.querySelector('.nv-copy-fallback');
childDelay: 170,
    if (input) { input.remove(); }
lockMs: 800,
    input = document.createElement('input');
gap: 10,
    input.className = 'nv-copy-fallback';
width: 480,
    input.readOnly = true;
wideWidth: 620,
    input.value = value;
grace: 160,
    input.setAttribute('aria-label', '复制失败,请手动选择文字');
lockedGrace: 430
    if (button.parentNode) { button.parentNode.insertBefore(input, button.nextSibling); }
};
    input.focus();
var reduceMotion = window.matchMedia && window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches;
    input.select();
var coarse = window.matchMedia && window.matchMedia( '(hover: none), (pointer: coarse)' ).matches;
    button.textContent = '请手动复制';
var termIndex = null;
    window.setTimeout(function () { if (input.isConnected) { input.remove(); } button.textContent = old; }, 12000);
var termLoading = null;
  }
var state = {
  if (navigator.clipboard && navigator.clipboard.writeText && window.isSecureContext) {
source: null,
    navigator.clipboard.writeText(value).then(done, fallback);
pendingSource: null,
  } else {
stack: [],
    fallback();
pointer: { x: 0, y: 0 },
  }
pendingRoot: 0,
};
pendingChild: 0,
closeAllTimer: 0,
closeChildTimer: 0,
closeChildIndex: -1,
single: false
};


/* Shared cached loader for the term JSON index (read-only consumers: NvLock preview
function clearTimer( key ) {
  and the unified page footer). The editor keeps its own uncached fetch to read the
if ( state[ key ] ) { clearTimeout( state[ key ] ); state[ key ] = 0; }
  latest revision + basetimestamp for conflict-safe saves. */
}
window.nvTermData = ( function () {
function closest( el, sel ) { return el && el.closest ? el.closest( sel ) : null; }
var cached = null, loading = null;
function norm( s ) {
return function () {
return String( s || '' ).replace( /_/g, ' ' ).replace( /\s+/g, ' ' ).trim().toLowerCase();
if ( cached ) { return Promise.resolve( cached ); }
}
if ( loading ) { return loading; }
function termHref( term ) {
var url = mw.util.getUrl( 'Module:术语库/data.json', { action: 'raw' } );
if ( term.article ) { var u = mw.util.getUrl( term.article ); return term.section ? u + '#' + encodeURIComponent( term.section ) : u; }
loading = fetch( url, { credentials: 'same-origin' } ).then( function ( r ) {
return mw.util.getUrl( '术语库' ) + '#' + term.id;
if ( !r.ok ) { throw new Error( 'terms-' + r.status ); }
}
return r.json();
function isNavigationLink( a ) {
} ).then( function ( data ) {
return !! closest( a, '.nv-chapter-nav, .nv-home, .nv-card, .toc, .catlinks, .printfooter' );
cached = data;
}
loading = null;
 
return data;
function targetOf( a ) {
} ).catch( function ( err ) {
if ( !a || !a.getAttribute ) { return null; }
loading = null;
var raw = a.getAttribute( 'href' ) || '';
throw err;
if ( !raw || raw.charAt( 0 ) === '#' || /^(javascript|mailto|tel):/i.test( raw ) ) { return null; }
} );
var url;
return loading;
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; }
/* Page-backed terms. Native pages/categories/redirects are the catalogue; the
if ( url.searchParams.get( 'redlink' ) || url.searchParams.get( 'oldid' ) || url.searchParams.get( 'diff' ) ) { return null; }
  existing JSON supplies compatible IDs, explicit aliases and section entries. */
var title = null;
window.nvTermCatalog = ( function () {
if ( url.pathname.indexOf( '/wiki/' ) === 0 ) {
'use strict';
try { title = decodeURIComponent( url.pathname.slice( 6 ) ); } catch ( e ) {}
var cached, loading, loadedAt = 0;
} else if ( url.searchParams.get( 'title' ) ) {
var excluded = new Set( [ '索引页面', '站点导航', '帮助与指南' ] );
title = url.searchParams.get( 'title' );
var maintenance = new Set( [ '术语', '资料', '已锚定', '需要改进', '待改进', '剧透', '核心设定' ] );
}
function norm( value ) { return String( value || '' ).replace( /_/g, ' ' ).trim().toLowerCase(); }
if ( !title ) { return null; }
function readPages() {
title = title.replace( /_/g, ' ' ).trim();
var pages = new Map(), api = new mw.Api();
if ( /^(Special|File|Category|MediaWiki|Module|Template|Help|User|Project|Draft|Gadget):/i.test( title ) ) { return null; }
function read( continuation ) {
try {
return api.get( Object.assign( {
if ( mw.Title && new mw.Title( title ).namespace !== 0 ) { return null; }
action: 'query', formatversion: 2, generator: 'allpages', gapnamespace: 0,
} catch ( err ) { return null; }
gapfilterredir: 'nonredirects', gaplimit: 'max',
return { title: title, hash: url.hash ? decodeURIComponent( url.hash.slice( 1 ) ) : '' };
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 isReference( a ) {
}
return !! closest( a, 'sup.reference, .reference, [role="doc-noteref"], .mw-cite-backlink, .references a' );
function combine( pages, metadata ) {
}
var terms = [], targets = Object.create( null ), order = ( metadata.categoryOrder || [] ).slice();
function isBody( a ) { return !! closest( a, '.mw-parser-output' ); }
pages.forEach( function ( page ) {
 
var categories = Array.from( new Set( ( page.categories || [] ).map( function ( cat ) {
function fetchTerms() {
return cat.title.replace( /^(Category|分类):/, '' );
if ( termIndex ) { return Promise.resolve( termIndex ); }
} ) ) );
if ( termLoading ) { return termLoading; }
if ( page.missing || page.ns !== 0 || !page.length || page.pageprops &&
termLoading = window.nvTermCatalog().then( function ( data ) {
Object.prototype.hasOwnProperty.call( page.pageprops, 'disambiguation' ) ||
var byId = Object.create( null );
categories.some( function ( cat ) { return excluded.has( cat ); } ) ||
var byTitle = Object.create( null );
[ '首页', '术语库', '术语库/编辑', '作者入口' ].indexOf( page.title ) >= 0 ) { return; }
var byArticle = Object.create( null );
var term = {
var bySection = Object.create( null );
id: 'page-' + page.pageid, pageid: page.pageid, revid: page.lastrevid,
var unique = Object.create( null );
name: page.title, article: page.title, aliases: [], legacyIds: [],
( data.terms || [] ).forEach( function ( t ) {
categories: categories.filter( function ( cat ) { return !maintenance.has( cat ) && !/^使用.*的页面$/.test( cat ); } )
byId[ t.id ] = t;
};
( t.legacyIds || [] ).forEach( function ( id ) { byId[ id ] = t; } );
( page.redirects || [] ).forEach( function ( redirect ) {
if ( t.article && ! t.section ) { byArticle[ norm( t.article ) ] = t; }
if ( !redirect.fragment ) { term.aliases.push( redirect.title ); }
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;
} );
} );
terms.push( term );
return termLoading;
[ page.title ].concat( term.aliases ).forEach( function ( title ) { targets[ norm( title ) ] = term; } );
}
} );
 
( metadata.terms || [] ).forEach( function ( record ) {
/* Preview the canonical page or requested section in full.
var page = targets[ norm( record.article || record.name ) ];
  Parsed content keeps its own styles and extension modules. */
if ( !page ) { return; }
var articleCache = Object.create( null );
var term = page;
var articleLoading = Object.create( null );
if ( record.section ) {
var previewSequence = 0;
term = Object.assign( {}, record, { pageid: page.pageid, article: page.article, categories: record.categories || [], legacyIds: [], curated: true } );
 
terms.push( term );
// Full articles can contain the same section/tab IDs as the host page or another card.
} else {
function scopePreview( article, body, title, section ) {
if ( !term.curated ) { term.id = record.id; }
var prefix = 'nv-preview-' + ( ++previewSequence ) + '-';
term.curated = true;
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(); }
}
}
term.legacyIds.push( record.id );
article.addEventListener( 'tabber:tabchange', function ( event ) {
term.categories = Array.from( new Set( term.categories.concat( record.categories || [] ) ) );
// The extension owns switching; a card must not rewrite the host page's fragment.
term.aliases = Array.from( new Set( ( term.aliases || [] ).concat( record.aliases || [], record.name || [] ) ) )
event.stopPropagation();
.filter( function ( alias ) { return norm( alias ) !== norm( term.name ); } );
if ( pending ) { requestAnimationFrame( scrollTarget ); }
} );
if ( event.detail.source === 'init' && ids.has( section ) ) {
terms.forEach( function ( term ) {
var target = article.querySelector( '#' + CSS.escape( ids.get( section ) ) );
term.categories.forEach( function ( category ) { if ( order.indexOf( category ) < 0 ) { order.push( category ); } } );
section = '';
} );
queueMicrotask( function () { jump( target ); } );
return { terms: terms, categoryOrder: order, automatic: true };
}
}
} );
return function ( force ) {
article.addEventListener( 'click', function ( event ) {
if ( !force && cached && Date.now() - loadedAt < 60000 ) { return Promise.resolve( cached ); }
var link = event.target.closest( 'a[href^="#' + prefix + '"]' );
if ( loading ) { return loading; }
if ( !link || link.classList.contains( 'tabber__tab' ) || event.ctrlKey || event.metaKey || event.shiftKey ) { return; }
loading = mw.loader.using( [ 'mediawiki.api', 'mediawiki.util' ] ).then( function () {
var target = article.querySelector( '#' + CSS.escape( mw.util.percentDecodeFragment( link.hash.slice( 1 ) ) ) );
return Promise.all( [ readPages(), window.nvTermData().catch( function () { return { terms: [] }; } ) ] );
if ( target ) { event.preventDefault(); jump( target ); }
} )
} );
.then( function ( values ) { cached = combine( values[ 0 ], values[ 1 ] ); loadedAt = Date.now(); loading = null; return cached; },
}
function ( error ) { loading = null; throw error; } );
return loading;
};
}() );


/* ==========================================================================
function articleTitleOf( term ) {
  nv-lock.js · 渐进锁定阅读链(B 路线:卡片内容为规范词条正文)
return term.article || term.name;
  - 真实 800ms 进度;满圈才 locked,可移入
}
  - 根词 180ms 延迟;未满圈离开立即取消
  - 每层以当次触发鼠标坐标为锚,不排队;卡片内容按规范词条正文加载(有界卡内可读)
  - 无深度上限;窄屏单面板可继续深入
  ========================================================================== */
( function () {
'use strict';


function boot() {
function applyPreviewReadingOrder( root ) {
if ( window.NvLock ) { return; }
var scope = root.classList && root.classList.contains( 'mw-parser-output' ) ? root : root.querySelector( '.mw-parser-output' );
 
if ( ! scope ) { return; }
var CFG = {
var heading = scope.querySelector( 'h2, h3, h4, h5, h6' );
rootDelay: 180,
var infobox = scope.querySelector( '.nv-infobox' );
childDelay: 170,
if ( ! heading || ! infobox ) { return; }
lockMs: 800,
var children = Array.prototype.slice.call( scope.children );
gap: 10,
var headingIndex = children.indexOf( heading );
width: 480,
if ( headingIndex < 0 ) {
wideWidth: 620,
var cursor = heading;
grace: 160,
while ( cursor && cursor.parentNode !== scope ) { cursor = cursor.parentNode; }
lockedGrace: 430,
headingIndex = children.indexOf( cursor );
fullPreviewMaxChars: 800,
}
fullPreviewMaxRows: 12
var infoboxIndex = children.indexOf( infobox );
};
if ( infoboxIndex < 0 || headingIndex < 0 || infoboxIndex > headingIndex ) { return; }
var reduceMotion = window.matchMedia && window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches;
var lead = children.slice( 0, headingIndex ).filter( function ( node ) {
var coarse = window.matchMedia && window.matchMedia( '(hover: none), (pointer: coarse)' ).matches;
return node !== infobox && ! node.classList.contains( 'nv-infobox' );
var pageName = ( mw.config && mw.config.get( 'wgPageName' ) ) || '';
} );
var mainPage = !! ( mw.config && mw.config.get( 'wgIsMainPage' ) ) || pageName === '首页';
var after = lead.length ? lead[ lead.length - 1 ].nextSibling : heading;
var termLibraryPage = pageName === '术语库';
if ( after !== infobox ) { scope.insertBefore( infobox, after ); }
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 ) {
function sanitizeArticle( root ) {
if ( state[ key ] ) { clearTimeout( state[ key ] ); state[ key ] = 0; }
var clone = root.cloneNode( true );
}
var drop = [
function closest( el, sel ) { return el && el.closest ? el.closest( sel ) : null; }
'.nv-term-card', '.nv-term-definition__link',
function norm( s ) {
'.nv-term-definition__article', '.toc', '.mw-editsection', '.novark-forum-links',
return String( s || '' ).replace( /_/g, ' ' ).replace( /\s+/g, ' ' ).trim().toLowerCase();
'#catlinks', '.catlinks', '.printfooter', '.mw-jump-link', '.mw-cite-backlink'
}
];
function termHref( term ) {
drop.forEach( function ( selector ) {
if ( term.article ) { var u = mw.util.getUrl( term.article ); return term.section ? u + '#' + encodeURIComponent( term.section ) : u; }
clone.querySelectorAll( selector ).forEach( function ( node ) { node.remove(); } );
return mw.util.getUrl( '术语库' ) + '#' + term.id;
} );
}
clone.querySelectorAll( 'script, iframe, object, embed' ).forEach( function ( node ) { node.remove(); } );
function isNavigationLink( a ) {
clone.querySelectorAll( 'a[href*="action=edit"]' ).forEach( function ( node ) { node.remove(); } );
return !! closest( a, '.nv-chapter-nav, .nv-home-grid, .nv-home-world, .nv-home-masthead, .nv-card, .toc, .catlinks, .printfooter' );
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 targetOf( a ) {
function fetchArticle( title, section ) {
if ( !a || !a.getAttribute ) { return null; }
var cacheKey = section ? title + '\x1f' + section : title;
var raw = a.getAttribute( 'href' ) || '';
if ( articleCache[ cacheKey ] ) { return Promise.resolve( articleCache[ cacheKey ] ); }
if ( !raw || raw.charAt( 0 ) === '#' || /^(javascript|mailto|tel):/i.test( raw ) ) { return null; }
if ( articleLoading[ cacheKey ] ) { return articleLoading[ cacheKey ]; }
var url;
var request;
try { url = new URL( a.href, location.href ); } catch ( e ) { return null; }
if ( section ) {
if ( url.origin !== location.origin ) { return null; }
request = new mw.Api().get( {
var action = url.searchParams.get( 'action' );
action: 'parse', formatversion: 2, page: title, prop: 'sections', redirects: 1
if ( action && action !== 'view' ) { return null; }
} ).then( function ( res ) {
if ( url.searchParams.get( 'redlink' ) || url.searchParams.get( 'oldid' ) || url.searchParams.get( 'diff' ) ) { return null; }
var sections = res && res.parse && res.parse.sections || [];
var title = null;
var wanted = norm( section );
if ( url.pathname.indexOf( '/wiki/' ) === 0 ) {
var found = sections.filter( function ( sec ) {
try { title = decodeURIComponent( url.pathname.slice( 6 ) ); } catch ( e ) {}
return norm( sec.anchor ) === wanted || norm( sec.line ) === wanted;
} else if ( url.searchParams.get( 'title' ) ) {
} )[ 0 ];
title = url.searchParams.get( 'title' );
return new mw.Api().get( {
}
action: 'parse', formatversion: 2, page: title, section: found ? found.index : undefined,
if ( !title ) { return null; }
prop: 'text|revid|modules|modulestyles',
title = title.replace( /_/g, ' ' ).trim();
disableeditsection: 1, disablelimitreport: 1, redirects: 1
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; }
} else {
} catch ( err ) { return null; }
request = new mw.Api().get( {
return { title: title, hash: url.hash ? decodeURIComponent( url.hash.slice( 1 ) ) : '' };
action: 'parse', formatversion: 2, page: title,
}
prop: 'text|revid|modules|modulestyles',
function isReference( a ) {
disableeditsection: 1, disablelimitreport: 1, redirects: 1
return !! closest( a, 'sup.reference, .reference, [role="doc-noteref"], .mw-cite-backlink, .references a' );
} );
}
}
function isBody( a ) { return !! closest( a, '.mw-parser-output' ); }
articleLoading[ cacheKey ] = request.then( function ( res ) {
 
var text = res && res.parse && res.parse.text;
function fetchTerms() {
if ( ! text ) { throw new Error( 'empty-parse' ); }
if ( termIndex ) { return Promise.resolve( termIndex ); }
var doc = new DOMParser().parseFromString( '<div>' + text + '</div>', 'text/html' );
if ( termLoading ) { return termLoading; }
var root = doc.querySelector( '.mw-parser-output' ) || doc.body;
termLoading = window.nvTermCatalog().then( function ( data ) {
var preview = sanitizeArticle( root );
var byId = Object.create( null );
var modules = []
var byTitle = Object.create( null );
.concat( ( res.parse.modules || [] ) )
var byArticle = Object.create( null );
.concat( ( res.parse.modulestyles || [] ) );
var bySection = Object.create( null );
var externalStyles = [];
var unique = Object.create( null );
doc.querySelectorAll( 'style' ).forEach( function ( style ) {
( data.terms || [] ).forEach( function ( t ) {
if ( ! root.contains( style ) ) { externalStyles.push( style.textContent || '' ); }
byId[ t.id ] = t;
} );
( t.legacyIds || [] ).forEach( function ( id ) { byId[ id ] = t; } );
articleCache[ cacheKey ] = { content: preview, title: res.parse.title, revid: res.parse.revid, modules: modules, styles: externalStyles };
if ( t.article && ! t.section ) { byArticle[ norm( t.article ) ] = t; }
delete articleLoading[ cacheKey ];
if ( t.section ) { bySection[ norm( t.article || t.name ) + '#' + norm( t.section ) ] = t; }
return articleCache[ cacheKey ];
[ t.name ].concat( t.aliases || [] ).forEach( function ( n ) {
}, function ( err ) {
var key = norm( n );
delete articleLoading[ cacheKey ];
if ( !key ) { return; }
throw err;
if ( Object.prototype.hasOwnProperty.call( byTitle, key ) && ( !byTitle[ key ] || byTitle[ key ].id !== t.id ) ) { byTitle[ key ] = null; }
} );
else { byTitle[ key ] = t; }
return articleLoading[ cacheKey ];
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 };
return termIndex;
} ).catch( function ( err ) {
console.warn( 'NvLock terms load failed', err );
termLoading = null;
throw err;
} );
return termLoading;
}
}


/* ---- B 路线:悬浮卡内容来源改为规范词条正文 --------------------------------
  旧行为:卡片只显示 JSON 短定义。
  新行为:复用规范词条解析正文,短内容完整显示,长内容只取简介与信息框;排除页头工具、
  页尾维护元数据与旧术语卡,不嵌整站壳。圆环/锁定/关闭/嵌套手感保持原样。 */
var articleCache = Object.create( null );
var articleLoading = Object.create( null );


function articleTitleOf( term ) {
function annotateTermLinks( scope, currentId ) {
return term.article || term.name;
scope.querySelectorAll( 'a[href]' ).forEach( function ( a ) {
}
var info = infoForTarget( a, currentId, true );
 
if ( ! info ) { return; }
function applyPreviewReadingOrder( root ) {
a.classList.add( 'nv-lock__term-link' );
var scope = root.classList && root.classList.contains( 'mw-parser-output' ) ? root : root.querySelector( '.mw-parser-output' );
a.setAttribute( 'data-nv-title', info.term.article || info.term.name );
if ( ! scope ) { return; }
if ( info.term.id && info.term.id.indexOf( 'page:' ) !== 0 ) {
var heading = scope.querySelector( 'h2, h3, h4, h5, h6' );
a.setAttribute( 'data-term-id', info.term.id );
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 );
function linkifyTerms( scope, currentId ) {
var drop = [
if ( ! termIndex ) { return; }
'.nv-term-card', '.nv-term-definition__link',
var walker = document.createTreeWalker( scope, NodeFilter.SHOW_TEXT, {
'.nv-term-definition__article', '.toc', '.mw-editsection', '.novark-forum-links',
acceptNode: function ( node ) {
'#catlinks', '.catlinks', '.printfooter', '.mw-jump-link', '.mw-cite-backlink'
var parent = node.parentElement;
];
if ( ! parent ) { return NodeFilter.FILTER_REJECT; }
drop.forEach( function ( selector ) {
if ( parent.closest( 'a, table, h1, h2, h3, h4, h5, h6, caption, sup, .nv-lock__header' ) ) {
clone.querySelectorAll( selector ).forEach( function ( node ) { node.remove(); } );
return NodeFilter.FILTER_REJECT;
}
return node.nodeValue && node.nodeValue.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
}
} );
} );
clone.querySelectorAll( 'script, iframe, object, embed' ).forEach( function ( node ) { node.remove(); } );
var nodes = [];
clone.querySelectorAll( 'a[href*="action=edit"]' ).forEach( function ( node ) { node.remove(); } );
while ( walker.nextNode() ) { nodes.push( walker.currentNode ); }
clone.querySelectorAll( '*' ).forEach( function ( node ) {
nodes.forEach( function ( node ) {
Array.prototype.slice.call( node.attributes || [] ).forEach( function ( attr ) {
var text = node.nodeValue;
if ( /^on/i.test( attr.name ) ) { node.removeAttribute( attr.name ); }
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 );
}
} );
} );
// 大表包一层横向滚动容器,不撑出卡;图片按卡宽缩放。
}
clone.querySelectorAll( 'table' ).forEach( function ( table ) {
 
if ( table.closest( '.nv-lock__table' ) ) { return; }
function hydrateCard( layer ) {
var wrap = document.createElement( 'div' );
var body = layer.el && layer.el.querySelector( '.nv-lock__body' );
wrap.className = 'nv-lock__table';
if ( ! body ) { return; }
table.parentNode.insertBefore( wrap, table );
var title = articleTitleOf( layer.term );
wrap.appendChild( table );
var section = layer.term.section || '';
} );
function insert( entry ) {
clone.querySelectorAll( 'img' ).forEach( function (img ) {
if ( ! layer.el || ! layer.el.isConnected ) { return; }
img.removeAttribute( 'width' );
var content = entry && entry.content ? entry.content : entry;
img.removeAttribute( 'height' );
if ( ! content ) { return; }
img.loading = 'eager';
body.replaceChildren();
img.decoding = 'async';
var article = document.createElement( 'div' );
} );
article.className = 'nv-lock__article';
applyPreviewReadingOrder( clone );
article.setAttribute( 'lang', 'zh-Hans' );
return clone;
article.setAttribute( 'dir', 'ltr' );
}
article.setAttribute( 'data-preview-mode', 'full' );
 
( entry && entry.styles ? entry.styles : [] ).forEach( function ( css ) {
function previewContent( root ) {
var style = document.createElement( 'style' );
var text = root.cloneNode( true );
style.textContent = css;
var noise = 'style, .nv-infobox, .infobox, .nv-seatmap, .toc, .mw-references-wrap, .references, .nv-rule-switch, .nv-term-preview-trigger, nav';
article.appendChild( style );
text.querySelectorAll( noise ).forEach( function ( node ) { node.remove(); } );
var chars = ( text.textContent || '' ).replace( /\s+/g, ' ' ).trim().length;
var rows = text.querySelectorAll( 'table tr' ).length;
if ( chars <= CFG.fullPreviewMaxChars && rows <= CFG.fullPreviewMaxRows &&
!text.querySelector( '.mien-spell-filter, .mien-price-inline-calculator' ) ) {
return { content: root, mode: 'full' };
}
var summary = root.cloneNode( false );
root.querySelectorAll( 'style' ).forEach( function ( style ) { summary.appendChild( style.cloneNode( true ) ); } );
var paragraphs = Array.prototype.filter.call( root.querySelectorAll( 'p' ), function ( p ) {
return !p.closest( '.nv-infobox, .infobox, .nv-seatmap, .references, .toc, nav, .nv-chapter-nav, .nv-lock__more' ) &&
( p.textContent || '' ).trim().length > 0;
} );
var count = 0;
paragraphs.slice( 0, 2 ).forEach( function ( p, i ) {
var length = ( p.textContent || '' ).trim().length;
if ( i && count + length > 600 ) { return; }
summary.appendChild( p.cloneNode( true ) );
count += length;
} );
var infobox = root.querySelector( '.nv-infobox, .infobox, .nv-seatmap' );
if ( infobox ) { summary.appendChild( infobox.cloneNode( true ) ); }
if ( !paragraphs.length && !infobox ) {
var note = document.createElement( 'p' );
note.textContent = '本页以表格或列表为主,请打开条目阅读全文。';
summary.appendChild( note );
}
var notes = new Set();
summary.querySelectorAll( 'sup.reference a[href*="#"]' ).forEach( function ( a ) {
try { notes.add( decodeURIComponent( a.hash.slice( 1 ) ) ); } catch ( e ) {}
} );
if ( notes.size ) {
var references = document.createElement( 'ol' ); references.className = 'references';
root.querySelectorAll( 'ol.references > li' ).forEach( function ( li, i ) {
if ( notes.has( li.id ) ) { var clone = li.cloneNode( true ); clone.value = i + 1; references.appendChild( clone ); }
} );
} );
if ( references.children.length ) { summary.appendChild( references ); }
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();
}
}
}
return { content: summary, mode: 'summary' };
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 fetchArticle( title, section ) {
 
var cacheKey = section ? title + '\x1f' + section : title;
function samePageHash( target ) {
if ( articleCache[ cacheKey ] ) { return Promise.resolve( articleCache[ cacheKey ] ); }
var current = ( ( mw.config && mw.config.get( 'wgPageName' ) ) || '' ).replace( /_/g, ' ' );
if ( articleLoading[ cacheKey ] ) { return articleLoading[ cacheKey ]; }
return !! ( current && target && target.hash && target.title === current );
var request;
}
if ( section ) {
 
request = new mw.Api().get( {
function infoForTarget( a, currentId, insideCard ) {
action: 'parse', formatversion: 2, page: title, prop: 'sections', redirects: 1
if ( ! a || a.classList.contains( 'new' ) ) { return null; }
} ).then( function ( res ) {
if ( ! insideCard && a.closest( '.nv-lock' ) ) { return null; }
var sections = res && res.parse && res.parse.sections || [];
if ( a.closest( '.nv-lock__header' ) || isReference( a ) || isNavigationLink( a ) ) { return null; }
var wanted = norm( section );
var target = targetOf( a );
var found = sections.filter( function ( sec ) {
if ( ! target || samePageHash( target ) ) { return null; }
return norm( sec.anchor ) === wanted || norm( sec.line ) === wanted;
if ( ! termIndex ) { return null; }
} )[ 0 ];
var term = null;
return new mw.Api().get( {
var id = null;
action: 'parse', formatversion: 2, page: title, section: found ? found.index : undefined,
if ( a.closest( '.nv-term-ref' ) || target.title === '术语库' ) {
prop: 'text|revid|modules|modulestyles',
id = ( target.hash.match( /^term-\d+$/ ) || [] )[ 0 ] || null;
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 ) {
if ( id ) {
var text = res && res.parse && res.parse.text;
term = termIndex.byId[ id ] || null;
if ( ! text ) { throw new Error( 'empty-parse' ); }
if ( ! term ) { return null; }
var doc = new DOMParser().parseFromString( '<div>' + text + '</div>', 'text/html' );
} else if ( target.hash ) {
var root = doc.querySelector( '.mw-parser-output' ) || doc.body;
var pageTerm = termIndex.byArticle[ norm( target.title ) ] || termIndex.byTitle[ norm( target.title ) ];
var preview = previewContent( sanitizeArticle( root ) );
term = termIndex.bySection[ norm( pageTerm ? pageTerm.article : target.title ) + '#' + norm( target.hash ) ] || null;
var modules = []
if ( !term && pageTerm && !pageTerm.section ) {
.concat( ( res.parse.modules || [] ) )
term = Object.assign( {}, pageTerm, { id: pageTerm.id + '#' + target.hash, section: target.hash, name: pageTerm.name + ' · ' + target.hash } );
.concat( ( res.parse.modulestyles || [] ) );
}
var externalStyles = [];
if ( !term ) { return null; }
doc.querySelectorAll( 'style' ).forEach( function ( style ) {
} else {
if ( ! root.contains( style ) ) { externalStyles.push( style.textContent || '' ); }
term = termIndex.byArticle[ norm( target.title ) ] || termIndex.byTitle[ norm( target.title ) ] || null;
} );
if ( ! term || term.section ) { return null; }
articleCache[ cacheKey ] = { content: preview.content, mode: preview.mode, revid: res.parse.revid, modules: modules, styles: externalStyles };
}
delete articleLoading[ cacheKey ];
if ( term ) {
return articleCache[ cacheKey ];
if ( currentId && term.id === currentId ) { return null; }
}, function ( err ) {
return { id: term.id, term: term };
delete articleLoading[ cacheKey ];
}
throw err;
return null;
} );
return articleLoading[ cacheKey ];
}
}


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


function annotateTermLinks( scope, currentId ) {
function pointFromLink( a ) {
scope.querySelectorAll( 'a[href]' ).forEach( function ( a ) {
var r = a.getBoundingClientRect();
var info = infoForTarget( a, currentId, true );
return {
if ( ! info ) { return; }
x: Math.min( window.innerWidth - 8, Math.max( 8, r.left + r.width / 2 ) ),
a.classList.add( 'nv-lock__term-link' );
y: Math.min( window.innerHeight - 8, Math.max( 8, r.top + r.height / 2 ) )
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 anchorPoint( a ) {
// 只处理段落/列表等正文文本节点;已在链接、表格、标题、脚注里的文字不重复加链。
if ( state.pointer.x || state.pointer.y ) { return { x: state.pointer.x, y: state.pointer.y }; }
function linkifyTerms( scope, currentId ) {
return pointFromLink( a );
if ( ! termIndex || ! termIndex.unique ) { return; }
}
var keys = Object.keys( termIndex.unique ).filter( function ( key ) {
 
return !! termIndex.unique[ key ] && termIndex.unique[ key ].id !== currentId;
function makeCard( layer ) {
} ).sort( function ( a, b ) { return b.length - a.length; } );
var card = document.createElement( 'div' );
if ( ! keys.length ) { return; }
card.className = 'nv-lock';
var walker = document.createTreeWalker( scope, NodeFilter.SHOW_TEXT, {
card.setAttribute( 'role', 'dialog' );
acceptNode: function ( node ) {
card.setAttribute( 'aria-label', layer.term.name + ' 词条内容卡' );
var parent = node.parentElement;
card.setAttribute( 'data-depth', String( layer.depth ) );
if ( ! parent ) { return NodeFilter.FILTER_REJECT; }
card.innerHTML =
if ( parent.closest( 'a, table, h1, h2, h3, h4, h5, h6, caption, sup, .nv-lock__header' ) ) {
'<div class="nv-lock__header">' +
return NodeFilter.FILTER_REJECT;
'<button type="button" class="nv-lock__back" aria-label="返回上一层" title="返回上一层" hidden>←</button>' +
}
'<a class="nv-lock__title" href="#"></a>' +
return node.nodeValue && node.nodeValue.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
'<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>' +
var nodes = [];
'</svg>' +
while ( walker.nextNode() ) { nodes.push( walker.currentNode ); }
'</div>' +
nodes.forEach( function ( node ) {
'<div class="nv-lock__body"><p class="nv-lock__loading">正在读取词条…</p></div>';
var text = node.nodeValue;
var title = card.querySelector( '.nv-lock__title' );
var lower = text.toLowerCase();
title.href = termHref( layer.term );
var fragment = document.createDocumentFragment();
title.textContent = layer.term.name;
var i = 0, buffer = '';
var back = card.querySelector( '.nv-lock__back' );
while ( i < text.length ) {
back.addEventListener( 'click', function ( e ) {
var hit = null, hitKey = '';
e.preventDefault();
for ( var k = 0; k < keys.length; k++ ) {
e.stopPropagation();
var key = keys[ k ];
backOne();
if ( key.length > hitKey.length && lower.substr( i, key.length ) === key ) {
} );
hit = termIndex.unique[ key ];
card.addEventListener( 'mouseenter', function () {
hitKey = key;
clearTimer( 'closeAllTimer' );
}
clearTimer( 'closeChildTimer' );
}
if ( hit ) {
if ( buffer ) { fragment.appendChild( document.createTextNode( buffer ) ); buffer = ''; }
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;
} else {
buffer += text.charAt( i++ );
}
}
if ( buffer ) { fragment.appendChild( document.createTextNode( buffer ) ); }
node.parentNode.replaceChild( fragment, node );
} );
} );
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 hydrateCard( layer ) {
function setRing( layer, p ) {
var body = layer.el && layer.el.querySelector( '.nv-lock__body' );
if ( !layer.ring ) { return; }
if ( ! body ) { return; }
layer.progress = p;
var title = articleTitleOf( layer.term );
layer.ring.style.strokeDashoffset = String( 40.21 * ( 1 - p ) );
var section = layer.term.section || '';
if ( p >= 1 ) { layer.el.setAttribute( 'data-locked', 'true' ); }
var cacheKey = section ? title + '\x1f' + section : title;
}
function insert( entry ) {
function completeRing( layer ) {
if ( ! layer.el || ! layer.el.isConnected ) { return; }
if ( layer.raf ) { cancelAnimationFrame( layer.raf ); layer.raf = 0; }
var content = entry && entry.content ? entry.content : entry;
layer.locked = true;
if ( ! content ) { return; }
setRing( layer, 1 );
body.replaceChildren();
}
var article = document.createElement( 'div' );
function startRing( layer ) {
article.className = 'nv-lock__article';
if ( reduceMotion ) { completeRing( layer ); return; }
article.setAttribute( 'lang', 'zh-Hans' );
layer.locked = false;
article.setAttribute( 'dir', 'ltr' );
layer.startedAt = performance.now();
article.setAttribute( 'data-preview-mode', entry.mode || 'full' );
var tick = function ( now ) {
( entry && entry.styles ? entry.styles : [] ).forEach( function ( css ) {
var p = Math.min( 1, ( now - layer.startedAt ) / CFG.lockMs );
var style = document.createElement( 'style' );
setRing( layer, p );
style.textContent = css;
if ( p >= 1 ) {
article.appendChild( style );
layer.locked = true;
} );
layer.raf = 0;
article.appendChild( content.cloneNode( true ) );
return;
body.appendChild( article );
if ( entry.mode === 'summary' ) {
var more = document.createElement( 'a' );
more.className = 'nv-lock__more'; more.href = termHref( layer.term ); more.textContent = '阅读全文';
article.appendChild( more );
}
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();
}
}
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 );
}
}
function render( entry ) {
var chosen = null;
if ( ! layer.el || ! layer.el.isConnected ) { return; }
for ( var i = 0; i < candidates.length; i++ ) {
insert( entry );
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 ( articleCache[ cacheKey ] ) { render( articleCache[ cacheKey ] ); return; }
if ( ax >= l && ax <= l + w && ay >= t && ay <= t + h ) { continue; }
fetchArticle( title, section ).then( render, function () {
if ( overlapsSource( l, t ) ) { continue; }
if ( ! layer.el || ! layer.el.isConnected ) { return; }
chosen = { l: l, t: t };
body.replaceChildren();
break;
var error = document.createElement( 'p' );
}
error.className = 'nv-lock__error';
if ( !chosen && src ) {
error.textContent = '词条内容暂未读取成功。';
var preferred = [
body.appendChild( error );
{ 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 }
 
];
function samePageHash( target ) {
for ( var j = 0; j < preferred.length; j++ ) {
var current = ( ( mw.config && mw.config.get( 'wgPageName' ) ) || '' ).replace( /_/g, ' ' );
var cl = Math.max( 8, Math.min( preferred[ j ].l, vw - w - 8 ) );
return !! ( current && target && target.hash && target.title === current );
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; }
function infoForTarget( a, currentId, insideCard ) {
chosen = { l: cl, t: ct };
if ( ! a || a.classList.contains( 'new' ) ) { return null; }
break;
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 ) {
if ( !chosen ) {
term = termIndex.byId[ id ] || null;
chosen = {
if ( ! term ) { return null; }
l: Math.max( 8, Math.min( ax + g, vw - w - 8 ) ),
} else if ( target.hash ) {
t: Math.max( 8, Math.min( ay - 28, vh - h - 8 ) )
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 ) {
card.style.width = ( layer.width ? Math.min( layer.width, vw - 24 ) : Math.min( CFG.width, vw - 24 ) ) + 'px';
if ( currentId && term.id === currentId ) { return null; }
card.style.left = chosen.l + 'px';
return { id: term.id, term: term };
card.style.top = chosen.t + 'px';
}
card.style.zIndex = String( 1200 + layer.depth * 10 );
return null;
layer.bounds = { left: chosen.l, top: chosen.t, width: w, height: h };
}
}


function termFromAnchor( a ) {
function fitLayer( layer, article ) {
if ( ! a || ! isBody( a ) || isReference( a ) || a.closest( '.nv-lock' ) ) { return null; }
if ( ! layer || ! layer.el ) { return; }
return infoForTarget( a, null, false );
var vw = window.innerWidth;
}
if ( coarse ) {
 
layer.width = Math.max( 240, vw - 24 );
function pointFromLink( a ) {
return;
var r = a.getBoundingClientRect();
}
return {
var hasInfobox = !! article.querySelector( '.nv-infobox, .infobox, .nv-seatmap' );
x: Math.min( window.innerWidth - 8, Math.max( 8, r.left + r.width / 2 ) ),
var hasTable = !! article.querySelector( 'table' );
y: Math.min( window.innerHeight - 8, Math.max( 8, r.top + r.height / 2 ) )
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 );
function anchorPoint( a ) {
if ( ! hasInfobox && ! hasTable && text.length < 180 ) { width = 400; }
if ( state.pointer.x || state.pointer.y ) { return { x: state.pointer.x, y: state.pointer.y }; }
layer.width = Math.max( 320, Math.min( width, vw - 24 ) );
return pointFromLink( a );
layer.el.style.width = layer.width + 'px';
positionLayer( layer );
}
}


function makeCard( layer ) {
function applyVisibility() {
var card = document.createElement( 'div' );
state.single = coarse;
card.className = 'nv-lock';
var top = state.stack[ state.stack.length - 1 ];
card.setAttribute( 'role', 'dialog' );
state.stack.forEach( function ( layer, i ) {
card.setAttribute( 'aria-label', layer.term.name + ' 词条内容卡' );
var visible = ! state.single || i === state.stack.length - 1;
card.setAttribute( 'data-depth', String( layer.depth ) );
layer.el.style.display = visible ? 'flex' : 'none';
card.innerHTML =
layer.el.classList.toggle( 'nv-lock--single', state.single );
'<div class="nv-lock__header">' +
layer.el.querySelector( '.nv-lock__back' ).hidden = ! state.single || state.stack.length < 2;
'<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 () {
if ( top ) {
clearTimer( 'closeAllTimer' );
top.el.setAttribute( 'aria-modal', state.single ? 'true' : 'false' );
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 ) {
function createLayer( term, depth, anchor, sourceLink, locked ) {
if ( !layer.ring ) { return; }
var layer = {
layer.progress = p;
term: term,
layer.ring.style.strokeDashoffset = String( 40.21 * ( 1 - p ) );
depth: depth,
if ( p >= 1 ) { layer.el.setAttribute( 'data-locked', 'true' ); }
anchor: { x: anchor.x, y: anchor.y },
}
sourceLink: sourceLink || null,
function completeRing( layer ) {
locked: !! locked,
if ( layer.raf ) { cancelAnimationFrame( layer.raf ); layer.raf = 0; }
progress: 0,
layer.locked = true;
raf: 0,
setRing( layer, 1 );
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 startRing( layer ) {
 
if ( reduceMotion ) { completeRing( layer ); return; }
function removeFrom( index, keepSource ) {
layer.locked = false;
if ( index < 0 ) { index = 0; }
layer.startedAt = performance.now();
while ( state.stack.length > index ) {
var tick = function ( now ) {
var layer = state.stack.pop();
var p = Math.min( 1, ( now - layer.startedAt ) / CFG.lockMs );
if ( layer.raf ) { cancelAnimationFrame( layer.raf ); layer.raf = 0; }
setRing( layer, p );
if ( layer.el ) { layer.el.remove(); }
if ( p >= 1 ) {
}
layer.locked = true;
if ( ! keepSource ) {
layer.raf = 0;
state.source = null;
return;
state.pendingSource = null;
}
}
layer.raf = requestAnimationFrame( tick );
applyVisibility();
};
layer.raf = requestAnimationFrame( tick );
}
}
 
function closeAll( keepSource ) {
function positionLayer( layer ) {
clearTimer( 'pendingRoot' ); clearTimer( 'pendingChild' ); clearTimer( 'closeAllTimer' ); clearTimer( 'closeChildTimer' );
var card = layer.el;
removeFrom( 0, !! keepSource );
var w = layer.width || card.offsetWidth || Math.min( CFG.width, window.innerWidth - 24 );
state.source = keepSource ? state.source : null;
var h = card.offsetHeight || 180;
state.pendingSource = null;
var vw = window.innerWidth, vh = window.innerHeight;
}
var ax = layer.anchor.x, ay = layer.anchor.y;
function backOne() {
var g = CFG.gap;
if ( state.stack.length <= 1 ) { closeAll( false ); return; }
var candidates = [
var layer = state.stack.pop();
{ l: ax + g, t: ay - 28 },
if ( layer ) {
{ l: ax - w - g, t: ay - 28 },
if ( layer.raf ) { cancelAnimationFrame( layer.raf ); }
{ l: ax + g, t: ay - h - g },
layer.el.remove();
{ 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;
applyVisibility();
for ( var i = 0; i < candidates.length; i++ ) {
clearTimer( 'closeAllTimer' );
var l = Math.max( 8, Math.min( candidates[ i ].l, vw - w - 8 ) );
clearTimer( 'closeChildTimer' );
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; }
function returnTo( index ) {
if ( overlapsSource( l, t ) ) { continue; }
if ( index < 0 || index >= state.stack.length ) { return; }
chosen = { l: l, t: t };
removeFrom( index + 1 );
break;
clearTimer( 'closeAllTimer' );
}
clearTimer( 'closeChildTimer' );
if ( !chosen && src ) {
applyVisibility();
var preferred = [
}
{ l: src.right + g, t: ay - 28 },
 
{ l: src.left - w - g, t: ay - 28 },
function openRoot( info, sourceLink, anchor, locked ) {
{ l: ax + g, t: src.bottom + g },
clearTimer( 'pendingRoot' ); clearTimer( 'pendingChild' ); clearTimer( 'closeAllTimer' ); clearTimer( 'closeChildTimer' );
{ l: ax - w - g, t: src.bottom + g }
removeFrom( 0, true );
];
state.source = sourceLink;
for ( var j = 0; j < preferred.length; j++ ) {
state.pendingSource = null;
var cl = Math.max( 8, Math.min( preferred[ j ].l, vw - w - 8 ) );
createLayer( info.term, 0, anchor, sourceLink, !! locked );
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; }
function openInfoAt( info, depth, sourceLink, anchor, locked ) {
if ( overlapsSource( cl, ct ) ) { continue; }
if ( ! info || ! info.term ) { return; }
chosen = { l: cl, t: ct };
while ( state.stack.length > depth ) {
break;
var old = state.stack.pop();
}
if ( old.raf ) { cancelAnimationFrame( old.raf ); }
if ( old.el ) { old.el.remove(); }
}
}
if ( !chosen ) {
createLayer( info.term, depth, anchor, sourceLink, !! locked );
chosen = {
}
l: Math.max( 8, Math.min( ax + g, vw - w - 8 ) ),
 
t: Math.max( 8, Math.min( ay - 28, vh - h - 8 ) )
function scheduleRoot( sourceLink, info ) {
};
clearTimer( 'pendingRoot' );
}
state.pendingSource = sourceLink;
card.style.width = ( layer.width ? Math.min( layer.width, vw - 24 ) : Math.min( CFG.width, vw - 24 ) ) + 'px';
state.pendingRoot = setTimeout( function () {
card.style.left = chosen.l + 'px';
state.pendingRoot = 0;
card.style.top = chosen.t + 'px';
if ( ! sourceLink.isConnected ) { return; }
card.style.zIndex = String( 1200 + layer.depth * 10 );
if ( state.stack.length ) { return; }
layer.bounds = { left: chosen.l, top: chosen.t, width: w, height: h };
openRoot( info, sourceLink, anchorPoint( sourceLink ), false );
}, CFG.rootDelay );
}
}


function fitLayer( layer, article ) {
function scheduleCloseAll() {
if ( ! layer || ! layer.el ) { return; }
if ( coarse ) { return; }
var vw = window.innerWidth;
clearTimer( 'closeAllTimer' );
if ( coarse ) {
state.closeAllTimer = setTimeout( function () {
layer.width = Math.max( 240, vw - 24 );
state.closeAllTimer = 0;
return;
closeAll( false );
}
}, state.stack[0] && state.stack[0].locked ? CFG.lockedGrace : CFG.grace );
var hasInfobox = !! article.querySelector( '.nv-infobox, .infobox, .nv-seatmap' );
}
var hasTable = !! article.querySelector( 'table' );
function scheduleCloseChild( index ) {
var hasMedia = !! article.querySelector( 'figure, .thumb, .nv-infobox__media, img' );
clearTimer( 'closeChildTimer' );
var text = ( article.textContent || '' ).replace( /\s+/g, ' ' ).trim();
state.closeChildIndex = index;
var width = hasInfobox || hasTable ? CFG.wideWidth : ( hasMedia ? 500 : 480 );
var guarded = state.stack[ index ];
if ( ! hasInfobox && ! hasTable && text.length < 180 ) { width = 400; }
state.closeChildTimer = setTimeout( function () {
layer.width = Math.max( 320, Math.min( width, vw - 24 ) );
state.closeChildTimer = 0;
layer.el.style.width = layer.width + 'px';
if ( state.closeChildIndex >= 0 ) { removeFrom( state.closeChildIndex ); }
positionLayer( layer );
state.closeChildIndex = -1;
}, guarded && guarded.locked ? CFG.lockedGrace : CFG.grace );
}
}


function applyVisibility() {
function layerAt( el ) {
state.single = coarse;
var card = closest( el, '.nv-lock' );
var top = state.stack[ state.stack.length - 1 ];
if ( ! card ) { return null; }
state.stack.forEach( function ( layer, i ) {
for ( var i = 0; i < state.stack.length; i++ ) {
var visible = ! state.single || i === state.stack.length - 1;
if ( state.stack[ i ].el === card ) { return state.stack[ i ]; }
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' );
}
}
return null;
}
}


function createLayer( term, depth, anchor, sourceLink, locked ) {
/* ---- page term source: hover/click ---- */
var layer = {
function onDocOver( e ) {
term: term,
var a = closest( e.target, 'a' );
depth: depth,
if ( e.target.closest( '.nv-lock' ) ) { return; }
anchor: { x: anchor.x, y: anchor.y },
if ( !a || !isBody( a ) || isReference( a ) ) { return; }
sourceLink: sourceLink || null,
var info = termFromAnchor( a );
locked: !! locked,
if ( !info ) { return; }
progress: 0,
if ( a === state.source ) {
raf: 0,
clearTimer( 'closeAllTimer' );
el: null,
clearTimer( 'closeChildTimer' );
ring: null
return;
};
}
var card = makeCard( layer );
if ( coarse ) { return; }
state.stack.push( layer );
if ( state.stack.length ) { closeAll( false ); }
document.body.appendChild( card );
scheduleRoot( a, info );
positionLayer( layer );
applyVisibility();
hydrateCard( layer );
if ( locked ) { completeRing( layer ); }
else { startRing( layer ); }
return layer;
}
}
 
function onDocOut( e ) {
function removeFrom( index, keepSource ) {
var a = closest( e.target, 'a' );
if ( index < 0 ) { index = 0; }
if ( !a ) { return; }
while ( state.stack.length > index ) {
if ( state.pendingSource === a && state.pendingRoot ) {
var layer = state.stack.pop();
clearTimer( 'pendingRoot' );
if ( layer.raf ) { cancelAnimationFrame( layer.raf ); layer.raf = 0; }
if ( layer.el ) { layer.el.remove(); }
}
if ( ! keepSource ) {
state.source = null;
state.pendingSource = null;
state.pendingSource = null;
}
}
applyVisibility();
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 closeAll( keepSource ) {
 
clearTimer( 'pendingRoot' ); clearTimer( 'pendingChild' ); clearTimer( 'closeAllTimer' ); clearTimer( 'closeChildTimer' );
function onCardOver( layer, e ) {
removeFrom( 0, !! keepSource );
var link = closest( e.target, '.nv-lock__term-link' );
state.source = keepSource ? state.source : null;
var idx = state.stack.indexOf( layer );
state.pendingSource = null;
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 backOne() {
function onCardOut( layer, e ) {
if ( state.stack.length <= 1 ) { closeAll( false ); return; }
var link = closest( e.target, '.nv-lock__term-link' );
var layer = state.stack.pop();
if ( ! link ) { return; }
if ( layer ) {
var to = e.relatedTarget;
if ( layer.raf ) { cancelAnimationFrame( layer.raf ); }
if ( to && ( link.contains( to ) || closest( to, '.nv-lock__term-link' ) === link ) ) { return; }
layer.el.remove();
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;
}
}
applyVisibility();
if ( to === state.source || ( state.source && state.source.contains( to ) ) ) {
clearTimer( 'closeAllTimer' );
removeFrom( idx + 1 );
clearTimer( 'closeChildTimer' );
return;
}
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 );
scheduleCloseChild( idx + 1 );
}
}


function scheduleRoot( sourceLink, info ) {
function onCardLeave( layer, e ) {
clearTimer( 'pendingRoot' );
var to = e.relatedTarget;
state.pendingSource = sourceLink;
if ( ! to ) { scheduleCloseAll(); return; }
state.pendingRoot = setTimeout( function () {
var targetLayer = layerAt( to );
state.pendingRoot = 0;
if ( targetLayer ) {
if ( ! sourceLink.isConnected ) { return; }
if ( targetLayer === layer ) { return; }
if ( state.stack.length ) { return; }
if ( targetLayer.depth > layer.depth ) { return; }
openRoot( info, sourceLink, anchorPoint( sourceLink ), false );
if ( layer.depth === 0 ) { return; }
}, CFG.rootDelay );
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 );
function scheduleCloseAll() {
return;
if ( coarse ) { return; }
}
clearTimer( 'closeAllTimer' );
if ( state.source && ( state.source === to || state.source.contains( to ) ) ) {
state.closeAllTimer = setTimeout( function () {
if ( layer.depth === 0 ) { return; }
state.closeAllTimer = 0;
removeFrom( layer.depth );
closeAll( false );
return;
}, 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;
scheduleCloseAll();
}
}


/* ---- page term source: hover/click ---- */
/* ---- mouse position, scroll/resize ---- */
function onDocOver( e ) {
document.addEventListener( 'mousemove', function ( e ) {
var a = closest( e.target, 'a' );
state.pointer.x = e.clientX;
if ( e.target.closest( '.nv-lock' ) ) { return; }
state.pointer.y = e.clientY;
if ( !a || !isBody( a ) || isReference( a ) ) { return; }
}, { passive: true } );
var info = termFromAnchor( a );
window.addEventListener( 'resize', function () {
if ( !info ) { return; }
if ( a === state.source ) {
clearTimer( 'closeAllTimer' );
clearTimer( 'closeChildTimer' );
return;
}
if ( coarse ) { return; }
if ( state.stack.length ) { closeAll( false ); }
if ( state.stack.length ) { closeAll( false ); }
scheduleRoot( a, info );
} );
}
 
function onDocOut( e ) {
/* ---- source hover ---- */
var a = closest( e.target, 'a' );
window.addEventListener( 'mouseover', onDocOver, true );
if ( !a ) { return; }
window.addEventListener( 'mouseout', onDocOut, true );
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 ) {
/* Article links always navigate. Touch preview has its own button. */
var link = closest( e.target, '.nv-lock__term-link' );
        function previewButtons(scope) {
var idx = state.stack.indexOf( layer );
            scope.querySelectorAll('a[href]').forEach(function (a) {
if ( idx < 0 ) { return; }
                if (a.nvPreviewButton || !isBody(a) || isReference(a)) { return; }
if ( link ) {
                var info = infoForTarget(a, null, !!a.closest('.nv-lock'));
var info = infoForTarget( link, layer.term.id, true );
                if (!info) { return; }
if ( ! info ) { return; }
                var button = document.createElement('button');
var existing = -1;
                button.type = 'button'; button.className = 'nv-term-preview-trigger';
state.stack.forEach( function ( l, i ) { if ( l.term.id === info.id ) { existing = i; } } );
                button.textContent = '◉'; button.title = '预览';
if ( existing >= 0 ) {
                button.setAttribute('aria-label', '预览「' + (a.textContent || info.term.name).trim() + '」');
clearTimer( 'pendingChild' );
                button.nvTermAnchor = a; a.nvPreviewButton = button;
state.pendingChild = setTimeout( function () {
                a.insertAdjacentElement('afterend', button);
state.pendingChild = 0;
            });
returnTo( existing );
        }
}, CFG.childDelay );
        document.addEventListener('pointerdown', function (e) {
return;
            if (e.pointerType === 'touch') { coarse = true; }
}
        }, { capture: true, passive: true });
var currentChild = state.stack[ idx + 1 ];
        document.addEventListener('click', function (e) {
if ( currentChild && currentChild.sourceLink === link ) {
            var button = closest(e.target, '.nv-term-preview-trigger');
clearTimer( 'closeChildTimer' );
            if (button && button.nvTermAnchor) {
return;
                var a = button.nvTermAnchor;
}
                var parent = closest(a, '.nv-lock');
if ( state.stack.length > idx + 1 ) { removeFrom( idx + 1 ); }
                var layer = parent && state.stack.filter(function (item) { return item.el === parent; })[0];
clearTimer( 'pendingChild' );
                var info = infoForTarget(a, layer && layer.term.id, !!parent);
state.pendingChild = setTimeout( function () {
                if (!info) { return; }
state.pendingChild = 0;
                e.preventDefault(); e.stopPropagation();
if ( ! link.isConnected ) { return; }
                if (layer) {
openInfoAt( info, idx + 1, link, anchorPoint( link ), false );
                    var existing = state.stack.findIndex(function (item) { return item.term.id === info.id; });
}, CFG.childDelay );
                    if (existing >= 0) { returnTo(existing); }
return;
                    else { openInfoAt(info, state.stack.indexOf(layer) + 1, a, pointFromLink(a), true); }
}
                } else { openRoot(info, a, pointFromLink(a), true); }
if ( state.stack.length > idx + 1 ) { removeFrom( idx + 1 ); }
                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 );
}
}
}
function onCardOut( layer, e ) {
document.addEventListener( 'keydown', onKeydown, true );
var link = closest( e.target, '.nv-lock__term-link' );
 
if ( ! link ) { return; }
/* ---- boot ---- */
var to = e.relatedTarget;
fetchTerms().then( function () { previewButtons( document ); } ).catch( function () {} );
if ( to && ( link.contains( to ) || closest( to, '.nv-lock__term-link' ) === link ) ) { return; }
window.NvLock = {
if ( state.pendingChild ) { clearTimer( 'pendingChild' ); }
version: '2.3.0-page-terms',
var idx = state.stack.indexOf( layer );
termCount: function () { return termIndex ? termIndex.raw.terms.length : -1; },
if ( idx < 0 ) { return; }
debugLink: function ( el ) { return { body: isBody( el ), target: targetOf( el ), ref: isReference( el ), nav: isNavigationLink( el ), info: infoForTarget( el, null, false ) }; },
var child = state.stack[ idx + 1 ];
debugInfo: function ( title ) { return { index: !! termIndex, byTitle: !!( termIndex && termIndex.byTitle[ norm( title ) ] ), bySection: !!( termIndex && termIndex.bySection[ norm( title ) ] ) }; },
if ( ! child || child.sourceLink !== link ) { return; }
isOpen: function () { return state.stack.length > 0; },
if ( to && child.el.contains( to ) ) { return; }
close: function () { closeAll( false ); },
if ( ! child.locked ) {
status: function () {
scheduleCloseChild( idx + 1 );
return {
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 ( 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 ) {
if ( window.mw && mw.loader && mw.loader.using ) {
var to = e.relatedTarget;
mw.loader.using( [ 'mediawiki.util', 'mediawiki.api' ] ).then( function () {
if ( ! to ) { scheduleCloseAll(); return; }
if ( document.readyState === 'loading' ) { document.addEventListener( 'DOMContentLoaded', boot ); }
var targetLayer = layerAt( to );
else { boot(); }
if ( targetLayer ) {
} );
if ( targetLayer === layer ) { return; }
} else if ( document.readyState === 'loading' ) {
if ( targetLayer.depth > layer.depth ) { return; }
document.addEventListener( 'DOMContentLoaded', boot );
if ( layer.depth === 0 ) { return; }
} else {
if ( layer.sourceLink && ( layer.sourceLink === to || layer.sourceLink.contains( to ) ) ) { return; }
boot();
// returning to an ancestor's blank area closes this branch, parent stays
}
removeFrom( layer.depth );
} )();
return;
}
if ( state.source && ( state.source === to || state.source.contains( to ) ) ) {
if ( layer.depth === 0 ) { return; }
removeFrom( layer.depth );
return;
}
if ( layer.depth > 0 ) {
scheduleCloseAll();
} else {
scheduleCloseAll();
}
}


/* ---- mouse position, scroll/resize ---- */
/* Source: table-layout.js */
document.addEventListener( 'mousemove', function ( e ) {
/* Shared table behaviour: wrap long description columns without intercepting input. */
state.pointer.x = e.clientX;
( function () {
state.pointer.y = e.clientY;
'use strict';
}, { passive: true } );
window.addEventListener( 'resize', function () {
if ( state.stack.length ) { closeAll( false ); }
} );


/* ---- source hover ---- */
function markWrappingTables( scope ) {
window.addEventListener( 'mouseover', onDocOver, true );
Array.prototype.forEach.call(
window.addEventListener( 'mouseout', onDocOut, true );
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 ); } );
} );
}() );


/* Article links always navigate. Touch preview has its own button. */
/* Source: page-footer.js */
        function previewButtons(scope) {
/* Page footer: references, term maintenance and discussion links. */
            scope.querySelectorAll('a[href]').forEach(function (a) {
( function () {
                if (a.nvPreviewButton || !isBody(a) || isReference(a)) { return; }
'use strict';
                var info = infoForTarget(a, null, !!a.closest('.nv-lock'));
if ( !window.mw || !mw.config ) { return; }
                if (!info) { return; }
var action = mw.config.get( 'wgAction' );
                var button = document.createElement('button');
if ( action !== 'view' || mw.config.get( 'wgNamespaceNumber' ) !== 0 ||
                button.type = 'button'; button.className = 'nv-term-preview-trigger';
mw.config.get( 'wgDiffNewId' ) !== null ) { return; }
                button.textContent = '◉'; button.title = '预览';
var pageTitle = ( mw.config.get( 'wgPageName' ) || '' ).replace( /_/g, ' ' );
                button.setAttribute('aria-label', '预览「' + (a.textContent || info.term.name).trim() + '」');
if ( !pageTitle || pageTitle === '首页' || pageTitle === '术语库' || pageTitle === '术语库/编辑' ) { return; }
                button.nvTermAnchor = a; a.nvPreviewButton = button;
var norm = function ( s ) { return String( s || '' ).replace( /_/g, ' ' ).replace( /\s+/g, ' ' ).trim().toLowerCase(); };
                a.insertAdjacentElement('afterend', button);
var openMenu = null;
            });
 
        }
function closeMenu() {
        document.addEventListener('pointerdown', function (e) {
if ( openMenu ) {
            if (e.pointerType === 'touch') { coarse = true; }
openMenu.parentNode.querySelector( '[aria-expanded]' ).setAttribute( 'aria-expanded', 'false' );
        }, { capture: true, passive: true });
openMenu.remove();
        document.addEventListener('click', function (e) {
openMenu = null;
            var button = closest(e.target, '.nv-term-preview-trigger');
}
            if (button && button.nvTermAnchor) {
}
                var a = button.nvTermAnchor;
 
                var parent = closest(a, '.nv-lock');
function positionMenu( menu, button ) {
                var layer = parent && state.stack.filter(function (item) { return item.el === parent; })[0];
var margin = 12, vw = window.innerWidth, vh = window.innerHeight;
                var info = infoForTarget(a, layer && layer.term.id, !!parent);
menu.style.width = Math.min( 320, vw - margin * 2 ) + 'px';
                if (!info) { return; }
menu.style.maxHeight = Math.min( 304, vh - margin * 2 ) + 'px';
                e.preventDefault(); e.stopPropagation();
var br = button.getBoundingClientRect();
                if (layer) {
var rect = menu.getBoundingClientRect();
                    var existing = state.stack.findIndex(function (item) { return item.term.id === info.id; });
var left = Math.max( margin, Math.min( br.left, vw - margin - rect.width ) );
                    if (existing >= 0) { returnTo(existing); }
var below = vh - br.bottom - margin;
                    else { openInfoAt(info, state.stack.indexOf(layer) + 1, a, pointFromLink(a), true); }
var above = br.top - margin;
                } else { openRoot(info, a, pointFromLink(a), true); }
var top = ( below >= Math.min( rect.height, 220 ) || below >= above ) ? br.bottom + 6 : br.top - 6 - rect.height;
                return;
top = Math.max( margin, Math.min( top, vh - margin - rect.height ) );
            }
menu.style.left = Math.round( left ) + 'px';
            if (state.stack.length && !closest(e.target, '.nv-lock')) { closeAll(false); }
menu.style.top = Math.round( top ) + 'px';
        }, true);
}
        document.addEventListener('focusin', function (e) {
 
            if (coarse) { return; }
function makeLink( label, href ) {
            var a = closest(e.target, 'a');
var a = document.createElement( 'a' );
            var info = a && termFromAnchor(a);
a.className = 'nv-page-footer__item';
            if (info) { openRoot(info, a, pointFromLink(a), true); }
a.href = href;
        });
a.textContent = label;
        mw.hook('wikipage.content').add(function (content) {
return a;
            var scope = content && content.jquery ? content[0] : content;
}
            if (scope && scope.querySelectorAll && termIndex) { previewButtons(scope); }
        });


function onKeydown( e ) {
function makeCopyButton( label, value ) {
if ( e.key === 'Escape' && state.stack.length ) {
var button = document.createElement( 'button' );
e.preventDefault();
button.type = 'button';
closeAll( false );
button.className = 'nv-page-footer__item';
}
button.textContent = label;
}
button.setAttribute( 'data-label', label );
document.addEventListener( 'keydown', onKeydown, true );
button.addEventListener( 'click', function () { window.nvCopyText( value, button ); } );
return button;
}


/* ---- boot ---- */
function makeMenuButton( label, items ) {
fetchTerms().then( function () { previewButtons( document ); } ).catch( function () {} );
var wrap = document.createElement( 'span' );
window.NvLock = {
wrap.className = 'nv-page-footer__menu-wrap';
version: '2.3.0-page-terms',
var button = document.createElement( 'button' );
termCount: function () { return termIndex ? termIndex.raw.terms.length : -1; },
button.type = 'button';
debugLink: function ( el ) { return { body: isBody( el ), target: targetOf( el ), ref: isReference( el ), nav: isNavigationLink( el ), info: infoForTarget( el, null, false ) }; },
button.className = 'nv-page-footer__item';
debugInfo: function ( title ) { return { index: !! termIndex, byTitle: !!( termIndex && termIndex.byTitle[ norm( title ) ] ), bySection: !!( termIndex && termIndex.bySection[ norm( title ) ] ) }; },
button.textContent = label;
isOpen: function () { return state.stack.length > 0; },
button.setAttribute( 'data-label', label );
close: function () { closeAll( false ); },
button.setAttribute( 'aria-haspopup', 'menu' );
status: function () {
button.setAttribute( 'aria-expanded', 'false' );
return {
button.addEventListener( 'click', function ( e ) {
terms: state.stack.map( function ( l ) { return l.term.name; } ),
e.stopPropagation();
locked: state.stack.map( function ( l ) { return !! l.locked; } ),
if ( openMenu && openMenu.parentNode === wrap ) { closeMenu(); return; }
progress: state.stack.map( function ( l ) { return l.progress; } ),
closeMenu();
bounds: state.stack.map( function ( l ) { return l.bounds; } ),
var menu = document.createElement( 'div' );
anchors: state.stack.map( function ( l ) { return l.anchor; } ),
menu.className = 'nv-footer-menu';
single: state.single
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;
if ( window.mw && mw.loader && mw.loader.using ) {
row.addEventListener( 'click', function () {
mw.loader.using( [ 'mediawiki.util', 'mediawiki.api' ] ).then( function () {
closeMenu();
if ( document.readyState === 'loading' ) { document.addEventListener( 'DOMContentLoaded', boot ); }
if ( item.href ) { location.href = item.href; }
else { boot(); }
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(); }
} );
} );
} else if ( document.readyState === 'loading' ) {
wrap.appendChild( button );
document.addEventListener( 'DOMContentLoaded', boot );
return wrap;
} else {
boot();
}
}
} )();


/* Accessible names for Citizen collapse buttons whose labels live in hidden icons. */
function currentSections() {
( function () {
var content = document.querySelector( '#mw-content-text .mw-parser-output' );
'use strict';
if ( ! content ) { return []; }
function label() {
var out = [];
document.querySelectorAll( '#citizen-toc .citizen-toc-toggle' ).forEach( function ( b ) {
content.querySelectorAll( 'h2, h3, h4, h5, h6' ).forEach( function ( heading ) {
if ( b.getAttribute( 'aria-label' ) ) { return; }
if ( heading.closest( '.nv-lock' ) ) { return; }
var t = ( b.textContent || '' ).replace( /\s+/g, ' ' ).trim();
var headline = heading.querySelector( '.mw-headline' );
if ( t ) { b.setAttribute( 'aria-label', t ); }
var anchor = heading.id || ( headline && headline.id );
} );
if ( ! anchor ) { return; }
document.querySelectorAll( '.citizen-section-toggle' ).forEach( function ( b ) {
var label = ( headline ? headline.textContent : heading.textContent ).trim();
if ( b.getAttribute( 'aria-label' ) ) { return; }
if ( ! label ) { return; }
var h = b.closest( '.citizen-section-heading' );
var panel = heading.closest( '.tabber__panel' );
if ( !h ) { return; }
if ( panel ) {
var clone = h.cloneNode( true );
var tab = document.getElementById( panel.getAttribute( 'aria-labelledby' ) );
clone.querySelectorAll( 'button, .citizen-section-toggle, .mw-editsection' ).forEach( function ( x ) { x.remove(); } );
if ( tab ) { label = tab.textContent.trim() + ' · ' + label; }
var title = ( clone.textContent || '' ).replace( /\s+/g, ' ' ).trim();
}
if ( title ) { b.setAttribute( 'aria-label', '折叠或展开「' + title + '」章节' ); }
out.push( { anchor: anchor, label: label } );
} );
} );
return out;
}
}
function boot() { label(); setTimeout( label, 350 ); }
if ( document.readyState === 'loading' ) { document.addEventListener( 'DOMContentLoaded', boot ); }
else { boot(); }
} )();


/* 2026-10-25 shared layout behaviour:
function nativeRef( term ) {
  - mark real first/second visual columns in scroll tables
var title = term.article || term.name;
  - reset only the newly shown table's local scrollLeft on tab switch
var target = title;
  No global wheel/touch interception. */
if ( term.section ) { target += '#' + term.section; }
( function () {
if ( ! term.section && norm( title ) === norm( term.name ) ) { return '[[' + title + ']]'; }
'use strict';
return '[[' + target + '|' + term.name + ']]';
}


function resetShownTableScroll( tab ) {
function removeSeparators( container ) {
var panelId = tab.getAttribute( 'aria-controls' );
if ( ! container ) { return; }
if ( !panelId ) {
container.querySelectorAll( ':scope > .nv-page-footer__sep' ).forEach( function ( node ) { node.remove(); } );
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 ) {
function addSeparators( container ) {
var tab = event.target.closest && event.target.closest( '.tabber__tab' );
if ( ! container ) { return; }
if ( tab ) {
removeSeparators( container );
resetShownTableScroll( tab );
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 markWrappingTables() {
function row( label ) {
Array.prototype.forEach.call(
var line = document.createElement( 'div' );
document.querySelectorAll( '.mw-parser-output .nv-table-scroll table' ),
line.className = 'nv-page-footer__row';
function ( table ) {
var name = document.createElement( 'span' );
if ( table.dataset.nvWrapChecked === '1' ) { return; }
name.className = 'nv-page-footer__label';
table.dataset.nvWrapChecked = '1';
name.textContent = label;
var firstRow = ( table.tHead && table.tHead.rows[ 0 ] ) || table.rows[ 0 ];
var items = document.createElement( 'span' );
if ( ! firstRow ) { return; }
items.className = 'nv-page-footer__items';
var headerText = ( firstRow.textContent || '' ).replace( /\s+/g, '' );
line.appendChild( name );
var cols = Array.prototype.reduce.call( firstRow.cells, function ( n, cell ) { return n + ( cell.colSpan || 1 ); }, 0 );
line.appendChild( items );
var longText = Array.prototype.some.call( table.querySelectorAll( 'td' ), function ( cell ) {
return { line: line, items: items };
return ( cell.textContent || '' ).trim().length > 60;
} );
var descriptionTable = /(描述|说明|备注)/.test( headerText );
if ( ! descriptionTable || cols > 5 || ! longText ) { return; }
table.classList.add( 'nv-table--wrap' );
var wrap = table.closest( '.nv-table-scroll' );
if ( wrap ) { wrap.classList.add( 'nv-table-scroll--wrap' ); }
}
);
}
}


function init() {
function pageFooterShell() {
markWrappingTables();
var existing = document.getElementById( 'nv-page-footer' );
document.addEventListener( 'click', onTabClick );
if ( existing ) { return existing; }
}
var footer = document.createElement( 'div' );
 
footer.id = 'nv-page-footer';
if ( document.readyState === 'loading' ) {
footer.className = 'nv-page-footer';
document.addEventListener( 'DOMContentLoaded', init, { once: true } );
var help = row( '帮助:' );
} else {
footer.appendChild( help.line );
init();
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 || []; } );
}


/* ===== 13: unified footer categories / help / discussion ===== */
function addHelp( footer, terms ) {
( function () {
var target = footer._help;
'use strict';
var pageLevel = terms.filter( function ( term ) {
if ( !window.mw || !mw.config ) { return; }
return ! term.section && norm( term.article || term.name ) === norm( pageTitle );
var action = mw.config.get( 'wgAction' );
} )[ 0 ] || null;
if ( action !== 'view' || mw.config.get( 'wgNamespaceNumber' ) !== 0 ) { return; }
var sections = terms.filter( function ( term ) {
var pageTitle = ( mw.config.get( 'wgPageName' ) || '' ).replace( /_/g, ' ' );
return term.section && norm( term.article ) === norm( pageTitle );
if ( !pageTitle || pageTitle === '首页' || pageTitle === '术语库' || pageTitle === '术语库/编辑' ) { return; }
} );
var norm = function ( s ) { return String( s || '' ).replace( /_/g, ' ' ).replace( /\s+/g, ' ' ).trim().toLowerCase(); };
if ( pageLevel && pageLevel.curated ) {
var openMenu = null;
target.appendChild( makeCopyButton( '复制术语引用', nativeRef( pageLevel ) ) );
 
target.appendChild( makeLink( '维护术语', mw.util.getUrl( '术语库/编辑', { term: pageLevel.id } ) ) );
function closeMenu() {
} else if ( sections.length === 1 ) {
if ( openMenu ) { openMenu.remove(); openMenu = null; }
target.appendChild( makeCopyButton( '复制术语引用', nativeRef( sections[ 0 ] ) ) );
}
target.appendChild( makeLink( '维护术语', mw.util.getUrl( '术语库/编辑', { term: sections[ 0 ].id } ) ) );
 
} else if ( sections.length > 1 ) {
function positionMenu( menu, button ) {
target.appendChild( makeMenuButton( '复制术语引用', sections.map( function ( term ) {
var margin = 12, vw = window.innerWidth, vh = window.innerHeight;
return { label: term.name, value: nativeRef( term ) };
menu.style.width = Math.min( 320, vw - margin * 2 ) + 'px';
} ) ) );
menu.style.maxHeight = Math.min( 304, vh - margin * 2 ) + 'px';
} else {
var br = button.getBoundingClientRect();
var list = currentSections();
var rect = menu.getBoundingClientRect();
target.appendChild( makeMenuButton( '复制引用', [ { label: '整页', value: '[[' + pageTitle + ']]' } ].concat( list.map( function ( section ) {
var left = Math.max( margin, Math.min( br.left, vw - margin - rect.width ) );
return { label: section.label, value: '[[' + pageTitle + '#' + section.anchor + '|' + section.label + ']]' };
var below = vh - br.bottom - margin;
} ) ) ) );
var above = br.top - margin;
if ( pageLevel ) {
var top = ( below >= Math.min( rect.height, 220 ) || below >= above ) ? br.bottom + 6 : br.top - 6 - rect.height;
target.appendChild( makeLink( '编辑词条', mw.util.getUrl( pageTitle, { action: 'edit' } ) ) );
top = Math.max( margin, Math.min( top, vh - margin - rect.height ) );
target.appendChild( makeMenuButton( '别名与章节', [ { label: '整页别名', href: mw.util.getUrl( '术语库/编辑', { name: pageTitle, article: pageTitle } ) } ].concat( list.map( function ( section ) {
menu.style.left = Math.round( left ) + 'px';
return { label: section.label, href: mw.util.getUrl( '术语库/编辑', { name: section.label, article: pageTitle, section: section.anchor } ) };
menu.style.top = Math.round( top ) + 'px';
} ) ) ) );
}
}
target.appendChild( makeLink( '历史', mw.util.getUrl( 'Special:History/' + pageTitle ) ) );
target.appendChild( makeLink( '链入页面', mw.util.getUrl( 'Special:WhatLinksHere/' + pageTitle ) ) );
addSeparators( target );
}
}


function makeLink( label, href ) {
 
var a = document.createElement( 'a' );
function start() {
a.className = 'nv-page-footer__item';
var footer = pageFooterShell();
a.href = href;
loadTerms().then( function ( terms ) { addHelp( footer, terms ); } ).catch( function () { if ( !footer._help.childElementCount ) { addHelp( footer, [] ); } } );
a.textContent = label;
return a;
}
}
if ( document.readyState === 'loading' ) { document.addEventListener( 'DOMContentLoaded', start, { once: true } ); }
else { start(); }
}() );


function makeCopyButton( label, value ) {
/* Source: page-status.js */
var button = document.createElement( 'button' );
/* ==========================================================================
button.type = 'button';
  Page status banners: read the page's categories and render framed
button.className = 'nv-page-footer__item';
  status banners at the top of the article. The
button.textContent = label;
  templates only categorise; the visual layer lives here and in
button.setAttribute( 'data-label', label );
  Template:状态/styles.css.
button.addEventListener( 'click', function () { window.nvCopyText( value, button ); } );
  ========================================================================== */
return button;
( 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 makeMenuButton( label, items ) {
function appendSource( body, source ) {
var wrap = document.createElement( 'span' );
if ( !source ) { return; }
wrap.className = 'nv-page-footer__menu-wrap';
[ 'note', 'discuss' ].forEach( function ( suffix ) {
var button = document.createElement( 'button' );
var sourceEl = source.querySelector( '.nv-status-' + suffix );
button.type = 'button';
if ( !sourceEl ) { return; }
button.className = 'nv-page-footer__item';
var box = document.createElement( 'div' );
button.textContent = label;
box.className = 'nv-status-banner__' + suffix;
button.setAttribute( 'data-label', label );
Array.prototype.forEach.call( sourceEl.childNodes, function ( node ) { box.appendChild( node.cloneNode( true ) ); } );
button.setAttribute( 'aria-haspopup', 'menu' );
if ( box.textContent.trim() || box.querySelector( 'a' ) ) {
button.setAttribute( 'aria-expanded', 'false' );
body.appendChild( box );
button.addEventListener( 'click', function ( e ) {
}
e.stopPropagation();
} );
if ( openMenu && openMenu.parentNode === wrap ) { closeMenu(); return; }
}
closeMenu();
 
var menu = document.createElement( 'div' );
function makeBanner( def, source ) {
menu.className = 'nv-footer-menu';
var banner = document.createElement( 'div' );
menu.setAttribute( 'role', 'menu' );
banner.className = 'nv-status-banner nv-status-banner--' + def.tone;
items.forEach( function ( item ) {
var icon = document.createElement( 'span' );
var row = document.createElement( 'button' );
icon.className = 'nv-status-banner__icon nv-icon nv-icon--' + def.icon;
row.type = 'button';
icon.setAttribute( 'aria-hidden', 'true' );
row.className = 'nv-footer-menu__item';
var body = document.createElement( 'div' );
row.textContent = item.label;
body.className = 'nv-status-banner__body';
row.addEventListener( 'click', function () {
var title = document.createElement( 'strong' );
closeMenu();
title.className = 'nv-status-banner__title';
if ( item.href ) { location.href = item.href; }
title.textContent = def.title;
else { window.nvCopyText( item.value, button ); }
body.appendChild( title );
} );
if ( def.text ) {
menu.appendChild( row );
var text = document.createElement( 'span' );
} );
text.className = 'nv-status-banner__text';
wrap.appendChild( menu );
text.textContent = def.text;
openMenu = menu;
body.appendChild( text );
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 = headline && headline.id;
if ( ! anchor ) { return; }
var label = ( headline.textContent || '' ).trim();
if ( ! label ) { return; }
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( '帮助:' );
var discussion = row( '讨论:' );
footer.appendChild( help.line );
footer.appendChild( discussion.line );
footer._help = help.items;
footer._discussion = discussion.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 ); }
}
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 ) {
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(); }
}() );
 
/* Rule version: preference and single-button view over native TabberNeue.
  Any explicit section/hash wins over the saved preference. */
( function () {
'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() {
try {
var value = window.localStorage.getItem( STORAGE_KEY );
return VERSIONS.indexOf( value ) >= 0 ? value : null;
} catch ( e ) {
return null;
}
}
 
function setPreference( version ) {
try {
window.localStorage.setItem( STORAGE_KEY, version );
} catch ( e ) {
// localStorage may be unavailable; preference is best-effort only.
}
}
 
function findRuleTabber() {
var tabbers = document.querySelectorAll( '.tabber' );
for ( var i = 0; i < tabbers.length; i++ ) {
if ( isRuleTabber( tabbers[ i ] ) && tabsOf( tabbers[ i ] ).length === 2 ) {
return tabbers[ i ];
}
}
return null;
}
 
function tabForVersion( tabber, version ) {
var tabs = tabsOf( tabber );
for ( var i = 0; i < tabs.length; i++ ) {
if ( tabs[ i ].getAttribute( 'href' ) === '#tabber-DND_' + version ) {
return tabs[ i ];
}
}
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 ) {
if ( !tabForVersion( tabber, version ) ) {
return false;
}
// 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' );
icon.className = 'nv-rule-version__icon';
icon.setAttribute( 'data-icon-slot', ICON_SLOT );
icon.setAttribute( 'data-icon-key', 'rule-common' );
icon.setAttribute( 'aria-hidden', 'true' );
var label = document.createElement( 'span' );
label.className = 'nv-rule-version__label';
var button = null;
if ( ! single ) {
button = document.createElement( 'button' );
button.type = 'button';
button.className = 'nv-rule-version__button';
button.setAttribute( 'aria-haspopup', 'menu' );
button.setAttribute( 'aria-expanded', 'false' );
button.setAttribute( 'data-icon-slot', ICON_SLOT );
button.appendChild( icon );
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 );
tabber.classList.add( 'nv-rule-version-enhanced' );
 
function sync() {
var tab = currentTab( tabber );
if ( ! tab ) { return; }
var version = versionOf( tab );
control.setAttribute( 'data-version', version || 'common' );
control.setAttribute( 'data-icon-key', iconKey( version ) );
icon.setAttribute( 'data-icon-key', iconKey( version ) );
label.textContent = labelOf( tab );
if ( button ) { button.setAttribute( 'aria-label', '当前规则版本:' + labelOf( tab ) + ',选择其他版本' ); }
if ( control.querySelector( '.nv-rule-version__menu' ) ) {
control.querySelectorAll( '.nv-rule-version__item' ).forEach( function ( item ) {
item.setAttribute( 'aria-current', item.getAttribute( 'data-version' ) === version ? 'true' : 'false' );
} );
}
}
 
if ( button ) {
button.addEventListener( 'click', function ( e ) {
e.stopPropagation();
if ( button.getAttribute( 'aria-expanded' ) === 'true' ) { closeMenus(); return; }
closeMenus();
var menu = document.createElement( 'div' );
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 ) {
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 ); } );
}() );
 
/* ==========================================================================
  Page status banners: read the page's categories and render framed
  status / setting-importance 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 IMPORTANCE = {
'核心设定': { icon: 'setting-core', tone: 'setting-core', title: '核心设定', text: '本页属于世界核心设定,修改事实性内容前请先核对相关条目。' },
'重要设定': { icon: 'setting-major', tone: 'setting-major', title: '重要设定', text: '本页属于重要设定,涉及的世界观信息请与相关条目保持一致。' },
'普通设定': { icon: 'setting-common', tone: 'setting-common', title: '普通设定', text: '本页属于普通设定资料。' },
'衍生设定': { icon: 'setting-derived', tone: 'setting-derived', title: '衍生设定', text: '本页属于衍生设定,可作为创作参考,但不自动进入主设定。' }
};
 
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 pageCategories() {
try {
return ( window.mw && mw.config && mw.config.get( 'wgCategories' ) ) || [];
} catch ( e ) {
return [];
}
}
appendSource( body, source );
banner.appendChild( icon );
banner.appendChild( body );
return banner;
}
}


function sourceFor( kind, type ) {
function render( $content ) {
var nodes = document.querySelectorAll( '.nv-status-source' );
if ( !document.body || !document.body.classList.contains( 'action-view' ) ) { return; }
for ( var i = 0; i < nodes.length; i++ ) {
if ( !window.mw || !mw.config || mw.config.get( 'wgNamespaceNumber' ) !== 0 ||
if ( nodes[ i ].getAttribute( 'data-nv-kind' ) === kind &&
mw.config.get( 'wgDiffNewId' ) !== null ) { return; }
nodes[ i ].getAttribute( 'data-nv-type' ) === type ) {
var content = document.querySelector( '#mw-content-text .mw-parser-output' );
return nodes[ i ];
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' ) || [];
return null;
var signature = JSON.stringify( cats );
}
if ( old && old.getAttribute( 'data-nv-categories' ) === signature ) { return; }
 
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;
while ( sourceEl.firstChild ) {
box.appendChild( sourceEl.firstChild.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() {
if ( !document.body || !document.body.classList.contains( 'action-view' ) ) { return; }
if ( !window.mw || !mw.config || mw.config.get( 'wgNamespaceNumber' ) !== 0 ) { return; }
var content = document.querySelector( '.mw-parser-output' );
if ( !content ) { return; }
var old = document.querySelector( '[data-nv-status-banner]' );
if ( old ) { old.remove(); }
if ( old ) { old.remove(); }
var cats = pageCategories();
var nodes = [];
var nodes = [];
var i;
var i;
for ( i = 0; i < cats.length; i++ ) {
if ( IMPORTANCE[ cats[ i ] ] ) {
nodes.push( makeBanner( IMPORTANCE[ cats[ i ] ], sourceFor( 'importance', cats[ i ] ) ) );
break;
}
}
for ( i = 0; i < STATUS_ORDER.length; i++ ) {
for ( i = 0; i < STATUS_ORDER.length; i++ ) {
if ( cats.indexOf( STATUS_ORDER[ i ] ) !== -1 ) {
if ( cats.indexOf( STATUS_ORDER[ i ] ) !== -1 ) {
nodes.push( makeBanner( STATUS[ STATUS_ORDER[ i ] ], sourceFor( 'status', STATUS_ORDER[ i ] ) ) );
nodes.push( makeBanner( STATUS[ STATUS_ORDER[ i ] ], sourceFor( content, 'status', STATUS_ORDER[ i ] ) ) );
break;
break;
}
}
第2,404行: 第1,737行:
stack.className = 'nv-status-stack';
stack.className = 'nv-status-stack';
stack.setAttribute( 'data-nv-status-banner', '' );
stack.setAttribute( 'data-nv-status-banner', '' );
stack.setAttribute( 'data-nv-categories', signature );
nodes.forEach( function ( node ) { stack.appendChild( node ); } );
nodes.forEach( function ( node ) { stack.appendChild( node ); } );
content.insertBefore( stack, content.firstChild );
content.insertBefore( stack, content.firstChild );
}
}


function init() {
mw.hook( 'wikipage.content' ).add( render );
render();
}
 
if ( document.readyState === 'loading' ) {
document.addEventListener( 'DOMContentLoaded', init );
} else {
init();
}
if ( window.mw && mw.hook ) {
mw.hook( 'wikipage.content' ).add( render );
}
}() );
 
/* ==========================================================================
  Rule-version pages: each version is a complete page. When a base entry has
  both version pages, show a compact top switch generated from page titles;
  the base page redirects to the default 3.5E page, so no source-level
  switcher is needed.
  ========================================================================== */
( function () {
'use strict';
 
var title = '';
try {
title = ( window.mw && mw.config && mw.config.get( 'wgPageName' ) ) || '';
} catch ( e ) { return; }
var match = /^(.+)\/规则 (3\.5E|5\.5E)$/.exec( title.replace( /_/g, ' ' ) );
if ( !match || !window.mw || mw.config.get( 'wgNamespaceNumber' ) !== 0 ) { return; }
 
var base = match[ 1 ];
var current = match[ 2 ];
var versions = [ '3.5E', '5.5E' ];
var pending = false;
 
function pageUrl( version ) {
var page = base + '/规则 ' + version;
if ( window.mw && mw.util && mw.util.getUrl ) {
return mw.util.getUrl( page );
}
return '/wiki/' + encodeURIComponent( page ).replace( /%20/g, '_' );
}
 
function render() {
if ( !document.body || !document.body.classList.contains( 'action-view' ) ) { return; }
var content = document.querySelector( '.mw-parser-output' );
if ( !content || content.querySelector( '[data-nv-rule-switch]' ) || pending ) { return; }
pending = true;
var api = '/api.php?action=query&format=json&formatversion=2&prop=info&titles=' +
encodeURIComponent( versions.map( function ( v ) { return base + '/规则 ' + v; } ).join( '|' ) );
fetch( api, { credentials: 'same-origin' } ).then( function ( response ) {
return response.json();
} ).then( function ( data ) {
var pages = ( data && data.query && data.query.pages ) || [];
var exists = {};
pages.forEach( function ( page ) { exists[ page.title ] = !page.missing; } );
var available = versions.filter( function ( v ) { return exists[ base + '/规则 ' + v ]; } );
if ( available.length < 2 ) { pending = false; return; }
 
var bar = document.createElement( 'div' );
bar.className = 'nv-rule-switch';
bar.setAttribute( 'data-nv-rule-switch', '' );
var label = document.createElement( 'span' );
label.className = 'nv-rule-switch__label';
label.textContent = '规则版本:';
bar.appendChild( label );
available.forEach( function ( version ) {
var link = document.createElement( 'a' );
link.href = pageUrl( version );
link.textContent = version;
if ( version === current ) {
link.className = 'is-current';
link.setAttribute( 'aria-current', 'page' );
}
bar.appendChild( link );
} );
if ( content.querySelector( '[data-nv-rule-switch]' ) ) { pending = false; return; }
content.insertBefore( bar, content.firstChild );
pending = false;
} ).catch( function () { pending = false; /* 无 JS/网络异常时不显示,正文仍可读 */ } );
}
 
if ( document.readyState === 'loading' ) {
document.addEventListener( 'DOMContentLoaded', render );
} else {
render();
}
if ( window.mw && mw.hook ) {
mw.hook( 'wikipage.content' ).add( render );
}
}() );
}() );

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