MediaWiki:Qlzq-Zuiming-History.js
Jump to navigation
Jump to search
Note: After publishing, you may have to bypass your browser's cache to see the changes.
- Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
- Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
- Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
(function () {
'use strict';
const selector = 'table.zuiming-history.zmh-matrix';
const words = {Add: '列入', Keep: '沿用', Drop: '退出', Out: '未列'};
function element(tag, text, cls) {
const node = document.createElement(tag);
if (text !== undefined) node.textContent = text;
if (cls) node.className = cls;
return node;
}
function parse(table) {
const versions = Array.from(table.rows[0].cells).slice(1).map(c => c.textContent.trim());
if (!versions.length || new Set(versions).size !== versions.length) throw Error('版本表头缺失或重复');
const names = new Set(), rows = [], changes = new Map();
let section = '';
for (const tr of Array.from(table.rows).slice(1)) {
const cols = Array.from(tr.cells, c => c.textContent.trim());
if (cols.length === 1 && tr.cells[0].tagName === 'TH') { section = cols[0]; continue; }
const match = /^(.*罪)(((?:第|《).+))$/.exec(cols[0]);
if (!match || names.has(match[1]) || cols.length > versions.length + 1) throw Error('请核对源码行:' + cols[0]);
const [, name, initialRef] = match;
names.add(name);
let active = false, ref = initialRef;
const events = versions.map((version, i) => {
const fields = (cols[i + 1] || '').split('/').map(x => x.trim());
const [state = '', group = '', newRef = '', note = ''] = fields;
const action = state || (active ? 'Keep' : 'Out');
if (fields.length > 4 || !(Object.hasOwn(words, action)) || active !== (action === 'Keep' || action === 'Drop'))
throw Error(version + ',' + name + ':无法从上一版转到 ' + action);
active = action === 'Add' || action === 'Keep';
if (newRef) ref = newRef;
const event = {action, active, ref, note, group, i, name};
if (group) {
const key = i + ':' + group;
if (!changes.has(key)) changes.set(key, []);
changes.get(key).push(event);
}
return event;
});
rows.push({name, section, events});
}
const byName = new Map(rows.map(row => [row.name, row]));
// Only connect separate names if the same source entry also retires an old name.
const related = new Map();
function family(start, limit) {
if (!related.has(limit)) related.set(limit, new Map());
const cache = related.get(limit);
if (cache.has(start)) return cache.get(start);
const members = new Set([start]);
for (const name of members) {
for (const e of byName.get(name).events.slice(0, limit + 1)) {
if (!e.group) continue;
const group = changes.get(e.i + ':' + e.group);
if (group.some(g => g.action === 'Drop' || g.action === 'Out'))
group.forEach(g => members.add(g.name));
}
}
members.forEach(n => cache.set(n, members));
return members;
}
return {versions, rows, byName, family};
}
function control(label, widget) {
const node = element('label', undefined, 'zmh-label');
node.append(element('span', label), widget);
return node;
}
function choose(options) {
const select = element('select');
options.forEach(([value, label]) => select.add(new Option(label, value)));
return select;
}
function viewer(table) {
if (table.dataset.zmhReady) return;
const {versions, rows, byName, family} = parse(table);
const last = versions.length - 1;
const panel = element('section', undefined, 'zmh-view');
const bar = element('div', undefined, 'zmh-bar');
const version = choose(versions.map((v, i) => [i, v]));
const mode = choose([['snapshot', '在册罪名'], ['changes', '本次修订'], ['all', '全部沿革']]);
const query = element('input'); query.type = 'search'; query.placeholder = '罪名、旧名或条号';
const latest = element('button', '回到最新'); latest.type = 'button';
const status = element('p', '', 'zmh-status'); status.setAttribute('aria-live', 'polite');
const list = element('div');
bar.append(control('视图', mode), control('版本', version), control('查找', query), latest);
panel.append(bar, status, list);
version.value = last;
function buildHistory(row, limit) {
const box = element('div', undefined, 'zmh-history');
const events = [];
for (const n of family(row.name, limit)) {
byName.get(n).events.slice(0, limit + 1).forEach(e => {
if (e.action === 'Add' || e.action === 'Drop' || e.group || e.note) events.push(e);
});
}
const rank = {Drop: 0, Out: 0, Keep: 1, Add: 2};
events.sort((a, b) => a.i - b.i || rank[a.action] - rank[b.action]);
for (const e of events) {
const line = element('p');
const tag = e.action === 'Out' && e.group ? '旁列' : words[e.action];
line.append(element('b', versions[e.i].split(' ')[0] + ' · ' + tag),
document.createTextNode(' ' + e.name + '(' + e.ref + ')' + (e.note ? ' ' + e.note : '')));
box.append(line);
}
return box;
}
const normalize = s => s.normalize('NFKC').replace(/\s+/g, '').toLowerCase();
function draw() {
const i = Number(version.value), all = mode.value === 'all', changes = mode.value === 'changes';
version.disabled = all;
const term = normalize(query.value);
const result = document.createDocumentFragment();
let section = '', ol, shown = 0, eligible = 0;
for (const row of rows) {
const e = row.events[i];
if (!all && (changes ? !(e.group || e.action === 'Add' || e.action === 'Drop') : !e.active)) continue;
eligible++;
const limit = all ? last : i;
const found = !term || Array.from(family(row.name, limit)).some(n => {
const es = byName.get(n).events.slice(0, limit + 1);
return es.some(x => (x.active || x.group) && normalize(n + ' ' + x.ref).includes(term));
});
if (!found) continue;
if (!ol || section !== row.section) {
section = row.section;
result.append(element('h3', section));
ol = element('ol'); ol.start = shown + 1; result.append(ol);
}
shown++;
const li = element('li'), details = element('details'), summary = element('summary');
const ref = all ? row.events[last].ref : e.ref;
summary.append(element('span', row.name, 'zmh-name'), element('small', ref));
if (changes) summary.append(element('em', e.action === 'Out' ? '高规旧名' : words[e.action]));
if (all) {
const enter = row.events.find(x => x.action === 'Add');
const drop = row.events.find(x => x.action === 'Drop');
const short = j => versions[j].split(' ')[0];
const range = enter ? short(enter.i) + '列入 · ' + (drop ? short(drop.i) + '退出' : '最新在册') : '高规旧名';
summary.append(element('em', range));
}
details.append(summary); li.append(details); ol.append(li);
details.addEventListener('toggle', () => {
if (details.open && details.children.length === 1) details.append(buildHistory(row, limit));
});
}
if (!shown) result.append(element('p', '没有匹配的罪名。'));
status.textContent = (all ? '全部沿革' : versions[i]) + ' ' + (term ? shown + ' / ' + eligible : shown) +
(changes ? ' 行涉及本次定名' : all ? ' 个历史名称' : ' 个在册罪名') + ' · 条款按定名文件所列,点罪名看沿革';
list.replaceChildren(result);
}
version.addEventListener('change', draw); mode.addEventListener('change', draw);
query.addEventListener('input', draw);
latest.addEventListener('click', () => { version.value = last; mode.value = 'snapshot'; query.value = ''; draw(); });
draw();
table.before(panel);
table.hidden = true;
table.style.display = 'none';
table.dataset.zmhReady = '1';
}
function mount(root) {
const tables = root.matches && root.matches(selector) ? [root] : root.querySelectorAll(selector);
for (const table of tables) {
try { viewer(table); }
catch (err) {
if (!table.previousElementSibling?.classList.contains('zmh-error'))
table.before(element('p', '罪名表校验未通过。' + err.message, 'zmh-error'));
}
}
}
if (window.mw && mw.hook) mw.hook('wikipage.content').add($content => mount($content[0]));
else if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => mount(document));
else mount(document);
})();