跳到正文
Novark

MediaWiki:Common.js

Phase1EmergencyAdmin​(留言 | 贡献)2026年11月4日 (三) 12:19的版本 (阅读脚本按页面用途初始化,术语目录复用原生短缓存)

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

  • Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5或Ctrl-R(Mac为⌘-R)
  • Google Chrome:按Ctrl-Shift-R(Mac为⌘-Shift-R)
  • Edge:按住Ctrl的同时单击刷新,或按Ctrl-F5。
/* 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,
			fullPreviewMaxChars: 800,
			fullPreviewMaxRows: 12
		};
		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;
		}

		/* Page content cache: show short entries in full, long entries as lead + infobox.
		   Parsed content is sanitized before entering the reading chain. */
		var articleCache = Object.create( null );
		var articleLoading = Object.create( null );

		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 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 previewContent( root ) {
			var text = root.cloneNode( true );
			var noise = 'style, .nv-infobox, .infobox, .nv-seatmap, .toc, .mw-references-wrap, .references, .nv-status-stack, .nv-term-preview-trigger, nav';
			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 ); }
			}
			return { content: summary, mode: 'summary' };
		}

		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 = previewContent( 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.content, mode: preview.mode, 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 || '';
			var cacheKey = section ? title + '\x1f' + section : title;
			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', entry.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 );
				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();
				}
			}
			function render( entry ) {
				if ( ! layer.el || ! layer.el.isConnected ) { return; }
				insert( entry );
			}
			if ( articleCache[ cacheKey ] ) { render( articleCache[ cacheKey ] ); return; }
			fetchArticle( title, section ).then( render, function () {
				if ( ! layer.el || ! layer.el.isConnected ) { return; }
				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;
			}
			if ( layer.depth > 0 ) {
				scheduleCloseAll();
			} else {
				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 = 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(); }
}() );

/* Source: page-status.js */
/* ==========================================================================
   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 RULES = {
		'3.5E规则': { icon: 'rule-35', tone: 'rule35', title: 'DND 3.5E 规则', text: '本页的规则数据采用 DND 3.5E。' },
		'5.5E规则': { icon: 'rule-55', tone: 'rule55', title: 'DND 5.5E 规则', text: '本页的规则数据采用 DND 5.5E。' },
		'通用规则': { icon: 'rule-common', tone: 'rule-common', title: '通用规则', text: '本页为通用规则说明,具体适用范围与判定以正文为准。' }
	};
	var versionTargets = null;

	function addVersionLinks( banner ) {
		var pageName = String( mw.config.get( 'wgPageName' ) || '' ).replace( /_/g, ' ' );
		var match = /^(.+)\/规则 (3\.5E|5\.5E)$/.exec( pageName );
		if ( !match ) { return; }
		var versions = [ '3.5E', '5.5E' ];
		var base = match[ 1 ];
		if ( !versionTargets ) {
			versionTargets = mw.loader.using( [ 'mediawiki.api', 'mediawiki.util' ] ).then( function () {
				return new mw.Api().get( {
					action: 'query', formatversion: 2, prop: 'info',
					titles: versions.map( function ( version ) { return base + '/规则 ' + version; } ).join( '|' )
				} );
			} ).then( function ( data ) {
				return new Set( ( data.query && data.query.pages || [] ).filter( function ( page ) {
					return !page.missing;
				} ).map( function ( page ) { return page.title; } ) );
			} );
		}
		versionTargets.then( function ( titles ) {
			if ( !banner.isConnected || versions.some( function ( version ) { return !titles.has( base + '/规则 ' + version ); } ) ) { return; }
			var links = document.createElement( 'div' );
			links.className = 'nv-status-banner__versions';
			versions.forEach( function ( version, index ) {
				if ( index ) { links.appendChild( document.createTextNode( ' · ' ) ); }
				var current = version === match[ 2 ];
				var node = document.createElement( current ? 'strong' : 'a' );
				node.textContent = version;
				if ( current ) { node.setAttribute( 'aria-current', 'page' ); }
				else { node.href = mw.util.getUrl( base + '/规则 ' + version ); }
				links.appendChild( node );
			} );
			banner.querySelector( '.nv-status-banner__body' ).appendChild( links );
		} ).catch( function () { /* 分类横幅与原生正文在网络异常时仍可读。 */ } );
	}

	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 rule = Object.keys( RULES ).find( function ( category ) { return cats.indexOf( category ) >= 0; } );
		if ( rule ) {
			var ruleBanner = makeBanner( RULES[ rule ], null );
			ruleBanner.setAttribute( 'data-nv-rule-version', rule );
			nodes.push( ruleBanner );
			addVersionLinks( ruleBanner );
		}
		var i;
		for ( i = 0; i < cats.length; i++ ) {
			if ( IMPORTANCE[ cats[ i ] ] ) {
				nodes.push( makeBanner( IMPORTANCE[ cats[ i ] ], sourceFor( content, 'importance', cats[ i ] ) ) );
				break;
			}
		}
		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 );
}() );