MediaWiki:Common.js:修订间差异
MediaWiki界面页面
更多操作
无编辑摘要 |
无编辑摘要 |
||
| (未显示同一用户的3个中间版本) | |||
| 第713行: | 第713行: | ||
/* ============================================ | /* ============================================ | ||
右侧独立侧栏 + 展开/收起按钮 | 右侧独立侧栏 + 展开/收起按钮 | ||
============================================ */ | ============================================ */ | ||
| 第735行: | 第720行: | ||
var MIN_DESKTOP = 1101; | var MIN_DESKTOP = 1101; | ||
var GAP | var GAP = 24; // 侧栏与 .mw-body 右边缘间距 (1.5rem) | ||
var | var COL_W = 320; // 侧栏宽度 (20rem) | ||
var | var EDGE = 8; // 侧栏与视口右边缘的最小间隙 | ||
function ensureSideColumn(mwBody) { | function ensureSideColumn(mwBody) { | ||
if (document.getElementById(COLUMN_ID)) return true; | if (document.getElementById(COLUMN_ID)) return true; | ||
| 第758行: | 第741行: | ||
} | } | ||
function ensureToggle(mwBody) { | function ensureToggle(mwBody) { | ||
if (document.getElementById(TOGGLE_ID)) return true; | if (document.getElementById(TOGGLE_ID)) return true; | ||
| 第774行: | 第756行: | ||
var isOpen = document.body.classList.toggle('anachronism-aside-open'); | var isOpen = document.body.classList.toggle('anachronism-aside-open'); | ||
btn.setAttribute('aria-expanded', isOpen ? 'true' : 'false'); | btn.setAttribute('aria-expanded', isOpen ? 'true' : 'false'); | ||
}); | }); | ||
| 第781行: | 第762行: | ||
} | } | ||
function reposition() { | function reposition() { | ||
if (window.innerWidth < MIN_DESKTOP) return; | if (window.innerWidth < MIN_DESKTOP) return; | ||
var col = document.getElementById(COLUMN_ID); | var col = document.getElementById(COLUMN_ID); | ||
var mwBody = document.querySelector('.mw-body'); | var mwBody = document.querySelector('.mw-body'); | ||
if (!col | if (!col || !mwBody) return; | ||
var mwRect = mwBody.getBoundingClientRect(); | var mwRect = mwBody.getBoundingClientRect(); | ||
var colLeft = Math.round(mwRect.right + GAP); | var colLeft = Math.round(mwRect.right + GAP); | ||
// | // 侧栏不能溢出视口右侧 | ||
var maxLeft = window.innerWidth - COL_W - EDGE; | |||
if (colLeft > maxLeft) colLeft = maxLeft; | |||
col.style.left = colLeft + 'px'; | col.style.left = colLeft + 'px'; | ||
// top 由 CSS 固定 5rem | |||
} | } | ||
function start() { | function start() { | ||
var mwBody = document.querySelector('.mw-body'); | var mwBody = document.querySelector('.mw-body'); | ||
| 第818行: | 第786行: | ||
if (!ensureSideColumn(mwBody)) return false; | if (!ensureSideColumn(mwBody)) return false; | ||
if (!ensureToggle(mwBody)) return false; | if (!ensureToggle(mwBody)) return false; | ||
// 默认展开 | |||
if (window.innerWidth >= MIN_DESKTOP) { | |||
document.body.classList.add('anachronism-aside-open'); | |||
var btn = document.getElementById(TOGGLE_ID); | |||
if (btn) btn.setAttribute('aria-expanded', 'true'); | |||
} | |||
reposition(); | reposition(); | ||
window.addEventListener('resize', reposition); | window.addEventListener('resize', reposition); | ||
new MutationObserver(reposition).observe(document.documentElement, { | new MutationObserver(reposition).observe(document.documentElement, { | ||
attributes: true, | attributes: true, | ||
attributeFilter: ['class'] | attributeFilter: ['class'] | ||
2026年10月2日 (五) 21:09的最新版本
/* ============================================
通用工具
============================================ */
window.Anachronism = window.Anachronism || {};
/**
* 等待某个条件成立后执行任务。
* 三路触发:立即尝试、定时轮询、DOM 变化时重试。
* 任一成功或超时后自动清理。
*
* @param {Function} taskFn 返回 true 表示任务完成
* @param {Object} [options]
* @param {number} [options.maxAttempts=100] 轮询最大次数
* @param {number} [options.intervalMs=100] 轮询间隔
* @param {number} [options.timeoutMs=15000] 硬超时
*/
window.Anachronism.waitFor = function (taskFn, options) {
options = options || {};
var maxAttempts = options.maxAttempts || 100;
var intervalMs = options.intervalMs || 100;
var timeoutMs = options.timeoutMs || 15000;
var attempts = 0;
var done = false;
function cleanup(timer, observer) {
if (done) return;
done = true;
if (timer) clearInterval(timer);
if (observer) observer.disconnect();
}
function tryRun() {
if (done) return false;
if (taskFn()) return true;
return false;
}
// 首次尝试
if (tryRun()) return;
var timer = setInterval(function () {
if (tryRun() || ++attempts >= maxAttempts) {
cleanup(timer, observer);
}
}, intervalMs);
var observer = new MutationObserver(function () {
if (tryRun()) cleanup(timer, observer);
});
observer.observe(document.body, { childList: true, subtree: true });
setTimeout(function () {
cleanup(timer, observer);
}, timeoutMs);
};
/* ============================================
侧边工具栏 Rail 管理器
============================================ */
window.Rail = (function () {
var items = [];
var activeId = null;
var panelEl, overlayEl, buttonsEl, contentEl, titleEl;
function ensureDOM() {
if (document.getElementById('rail-container')) return;
buttonsEl = document.createElement('div');
buttonsEl.id = 'rail-container';
buttonsEl.className = 'rail-container';
overlayEl = document.createElement('div');
overlayEl.id = 'rail-overlay';
overlayEl.className = 'rail-overlay';
panelEl = document.createElement('aside');
panelEl.id = 'rail-panel';
panelEl.className = 'rail-panel';
panelEl.innerHTML = [
'<div class="rail-panel__header">',
' <span class="rail-panel__title"></span>',
' <button class="rail-panel__close" type="button" aria-label="关闭">×</button>',
'</div>',
'<div class="rail-panel__content" id="rail-panel-content"></div>'
].join('');
titleEl = panelEl.querySelector('.rail-panel__title');
contentEl = panelEl.querySelector('#rail-panel-content');
document.body.appendChild(overlayEl);
document.body.appendChild(panelEl);
document.body.appendChild(buttonsEl);
panelEl.querySelector('.rail-panel__close').addEventListener('click', close);
overlayEl.addEventListener('click', close);
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape') close();
});
}
function createButton(item) {
var btn = document.createElement('button');
btn.type = 'button';
btn.className = 'rail-button fx-swap fx-pulse';
btn.setAttribute('data-rail-id', item.id);
btn.setAttribute('aria-label', item.label);
btn.setAttribute('title', item.label);
var iconDefault = item.icon || '●';
var iconActive = item.iconActive || iconDefault;
btn.innerHTML =
'<span class="fx-swap__a rail-button__icon fx-text-glow">' + iconDefault + '</span>' +
'<span class="fx-swap__b rail-button__icon fx-text-glow">' + iconActive + '</span>';
btn.addEventListener('click', function () {
if (activeId === item.id) {
close();
} else {
open(item);
}
});
return btn;
}
function highlightButtons() {
var all = buttonsEl.querySelectorAll('.rail-button');
for (var i = 0; i < all.length; i++) {
var id = all[i].getAttribute('data-rail-id');
all[i].classList.toggle('is-active', id === activeId);
}
}
function open(item) {
activeId = item.id;
titleEl.textContent = item.label;
contentEl.innerHTML = '<p class="rail-panel__loading">加载中…</p>';
highlightButtons();
document.body.classList.add('rail-open');
if (item.html) {
contentEl.innerHTML = item.html;
return;
}
if (item.template) {
var api = new mw.Api();
api.get({
action: 'parse',
page: item.template,
prop: 'text',
formatversion: '2'
}).done(function (data) {
if (activeId !== item.id) return;
if (data && data.parse && data.parse.text) {
contentEl.innerHTML = data.parse.text;
} else {
contentEl.innerHTML = '<p>加载失败。</p>';
}
}).fail(function () {
if (activeId !== item.id) return;
contentEl.innerHTML = '<p>加载失败。</p>';
});
} else {
contentEl.innerHTML = '<p>未配置内容。</p>';
}
}
function close() {
activeId = null;
document.body.classList.remove('rail-open');
if (buttonsEl) highlightButtons();
}
function init() {
ensureDOM();
buttonsEl.innerHTML = '';
items.forEach(function (item) {
buttonsEl.appendChild(createButton(item));
});
}
return {
register: function (id, options) {
options = options || {};
items.push({
id: id,
icon: options.icon || '●',
label: options.label || id,
html: options.html || null,
template: options.template || null
});
},
init: init,
open: open,
close: close
};
})();
/* ============================================
注册工具栏按钮
============================================ */
Rail.register('navigation', {
icon: '☰',
label: '导航',
template: 'Template:工具栏导航'
});
Rail.register('claim', {
icon: '!',
label: '公告',
template: 'Template:工具栏公告'
});
Rail.register('help', {
icon: '?',
label: '帮助',
template: 'Template:工具栏帮助'
});
Rail.register('settings', {
icon: '⚙',
label: '设置',
template: 'Template:工具栏设置'
});
/* ============================================
Rail 初始化
============================================ */
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', function () { Rail.init(); });
} else {
Rail.init();
}
/* ============================================
工具栏账户信息动态填充
============================================ */
(function () {
// 不显示的隐式用户组(user 也隐藏,但见下方 getGroupHtml 的兜底逻辑)
var HIDDEN_GROUPS = ['*', 'user', 'autoconfirmed', 'emailconfirmed'];
// 系统消息未加载时的中文兜底
var GROUP_NAME_FALLBACK = {
'sysop': '策展人',
'bureaucrat': '行政员',
'interface-admin': '织界者',
'interface_admin': '织界者',
'allowguest': '观察者',
'user': '旅人'
};
function formatDate(ms) {
if (!ms) return '—';
var d = new Date(ms);
return d.getFullYear() + '-' +
String(d.getMonth() + 1).padStart(2, '0') + '-' +
String(d.getDate()).padStart(2, '0');
}
function isMissing(msg) {
if (!msg) return true;
return msg.indexOf('\u29FC') !== -1 || msg.indexOf('⧼') !== -1;
}
function getGroupName(g) {
var txt = mw.msg('group-' + g + '-member');
if (!isMissing(txt)) return txt;
return GROUP_NAME_FALLBACK[g] || g;
}
function getGroupUrl(g) {
var page = mw.msg('grouppage-' + g);
if (!isMissing(page)) {
return mw.util.getUrl(page);
}
return mw.util.getUrl('Anachronism:' + getGroupName(g));
}
function buildGroupTag(g) {
var name = getGroupName(g);
var url = getGroupUrl(g);
return '<a href="' + url + '" class="rail-group-tag">' + name + '</a>';
}
function getGroupHtml(groups) {
var visible = groups.filter(function (g) {
return HIDDEN_GROUPS.indexOf(g) === -1;
});
// 没有任何"特殊"组时,若属于 user 组则显示"旅人",否则显示"无"
if (!visible.length) {
if (groups.indexOf('user') !== -1) {
return buildGroupTag('user');
}
return '无';
}
return visible.map(buildGroupTag).join('');
}
// 判断是否为管理/行政人员
function isStaff(groups) {
return groups.indexOf('sysop') !== -1 || groups.indexOf('bureaucrat') !== -1;
}
// ---- 通知未读数 ----
function updateNotificationButton(count) {
var btn = document.getElementById('rail-notification-btn');
if (!btn) return;
if (typeof count === 'number' && count > 0) {
btn.textContent = '通知 (' + count + ')';
} else {
btn.textContent = '通知';
}
}
function fetchUnreadCount() {
var cached = mw.config.get('wgEchoNotifsUnreadCount');
if (typeof cached === 'number') {
updateNotificationButton(cached);
return;
}
new mw.Api().get({
action: 'query',
meta: 'notifications',
notprop: 'count',
notfilter: '!read'
}).done(function (data) {
var count = 0;
try {
count = data.query.notifications.count || 0;
} catch (e) {}
updateNotificationButton(count);
}).fail(function () {
// 静默失败
});
}
function renderGuest(box) {
box.innerHTML = [
'<div class="rail-account-title">账户</div>',
'<p class="rail-account-guest">您的身份是访客</p>',
'<div class="rail-account-actions">',
' <a href="' + mw.util.getUrl('Special:UserLogin') + '" class="rail-action-button">登录</a>',
' <a href="' + mw.util.getUrl('Special:RequestAccount') + '" class="rail-action-button">申请账户</a>',
' <a href="' + mw.util.getUrl('Special:ListUsers') + '" class="rail-action-button">全部用户</a>',
'</div>'
].join('');
}
function renderUser(box) {
var userName = mw.config.get('wgUserName');
var groups = mw.config.get('wgUserGroups') || [];
var editCount = mw.config.get('wgUserEditCount');
var regTime = mw.config.get('wgUserRegistration');
// 基础按钮:贡献 / 监视列表 / 用户讨论 / 通知 / 全部用户
var actionButtons = [
' <a href="' + mw.util.getUrl('Special:Contributions/' + userName) + '" class="rail-action-button">贡献</a>',
' <a href="' + mw.util.getUrl('Special:Watchlist') + '" class="rail-action-button">监视列表</a>',
' <a href="' + mw.util.getUrl('User talk:' + userName) + '" class="rail-action-button">用户讨论</a>',
' <a href="' + mw.util.getUrl('Special:Notifications') + '" class="rail-action-button" id="rail-notification-btn">通知</a>',
' <a href="' + mw.util.getUrl('Special:ListUsers') + '" class="rail-action-button">全部用户</a>'
];
// 策展人 / 行政员额外显示"审批"
if (isStaff(groups)) {
actionButtons.push(
' <a href="' + mw.util.getUrl('Special:ConfirmAccounts') + '" class="rail-action-button">审批</a>'
);
}
box.innerHTML = [
'<div class="rail-account-title">账户:' + userName + '</div>',
'<div class="rail-account-groups"><span class="rail-account-groups__label">权限组:</span>' + getGroupHtml(groups) + '</div>',
'<div class="rail-account-actions">',
actionButtons.join('\n'),
'</div>',
'<div class="rail-account-stats">',
' <span>编辑数:' + (editCount != null ? editCount : '—') + '</span>',
' <span>加入时间:' + formatDate(regTime) + '</span>',
'</div>',
'<div class="rail-account-logout">',
' <a href="' + mw.util.getUrl('Special:UserLogout') + '" class="rail-action-button rail-action-button--danger">退出登录</a>',
'</div>'
].join('');
// 异步填充未读数
fetchUnreadCount();
}
function fillAccountInfo() {
var box = document.getElementById('rail-account-info');
if (!box || box.dataset.filled === '1') return;
box.dataset.filled = '1';
if (mw.config.get('wgUserName')) {
renderUser(box);
} else {
renderGuest(box);
}
}
function observeRailPanel() {
var target = document.getElementById('rail-panel-content');
if (!target) return;
var observer = new MutationObserver(fillAccountInfo);
observer.observe(target, { childList: true, subtree: true });
fillAccountInfo();
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', observeRailPanel);
} else {
observeRailPanel();
}
})();
/* ============================================
在 rail 面板中触发 Citizen 偏好设置面板
============================================ */
(function () {
function bindRailPreferences() {
var trigger = document.getElementById('rail-open-preferences');
if (!trigger || trigger.dataset.bound === '1') return;
trigger.dataset.bound = '1';
trigger.addEventListener('click', function () {
if (window.Rail && typeof Rail.close === 'function') {
Rail.close();
}
var details = document.getElementById('citizen-preferences-details');
if (details) {
details.open = true;
}
document.body.classList.add('citizen-preferences-shown');
// 插入关闭按钮(只插一次)
var card = document.getElementById('citizen-preferences-dropdown__card');
if (card && !card.querySelector('.citizen-preferences-close')) {
var closeBtn = document.createElement('button');
closeBtn.className = 'citizen-preferences-close';
closeBtn.type = 'button';
closeBtn.textContent = '×';
closeBtn.setAttribute('aria-label', '关闭');
closeBtn.addEventListener('click', function () {
document.body.classList.remove('citizen-preferences-shown');
var d = document.getElementById('citizen-preferences-details');
if (d) d.open = false;
});
card.insertBefore(closeBtn, card.firstChild);
}
});
}
// 点击面板外部关闭
document.addEventListener('click', function (e) {
if (!document.body.classList.contains('citizen-preferences-shown')) return;
var card = document.getElementById('citizen-preferences-dropdown__card');
var trigger = document.getElementById('rail-open-preferences');
if (!card) return;
if (card.contains(e.target)) return;
if (trigger && trigger.contains(e.target)) return;
document.body.classList.remove('citizen-preferences-shown');
var details = document.getElementById('citizen-preferences-details');
if (details) details.open = false;
});
// Esc 关闭
document.addEventListener('keydown', function (e) {
if (e.key !== 'Escape') return;
if (!document.body.classList.contains('citizen-preferences-shown')) return;
document.body.classList.remove('citizen-preferences-shown');
var details = document.getElementById('citizen-preferences-details');
if (details) details.open = false;
});
var observer = new MutationObserver(bindRailPreferences);
observer.observe(document.body, { childList: true, subtree: true });
bindRailPreferences();
})();
/* ============================================
评论区重定位:从主内容中移出,成为页面级独立块
============================================ */
(function () {
function tryRelocate() {
var existing = document.querySelector('.comments-body');
if (existing && existing.dataset.relocated === '1') {
return true; // 已处理过
}
var comments = document.querySelector('.mw-parser-output .comments-body');
if (!comments) return false;
var mwBody = document.querySelector('.mw-body');
if (!mwBody || !mwBody.parentNode) return false;
comments.dataset.relocated = '1';
comments.classList.add('comments-body--page-level');
mwBody.parentNode.insertBefore(comments, mwBody.nextSibling);
return true;
}
Anachronism.waitFor(tryRelocate);
})();
/* ============================================
评论区:把回复嵌套到父评论内部
Comments 扩展渲染的 DOM 是扁平的:
.c-item.full ← 顶层评论
.c-item.reply ← 回复(和 full 平级)
这里用 JS 把 .reply 移到前面最近一个 .full 的
.c-container 内部,形成真正的 DOM 嵌套。
============================================ */
(function () {
function nestReplies() {
var body = document.querySelector('.comments-body');
if (!body) return false;
if (body.dataset.repliesNested === '1') return true;
var items = Array.prototype.slice.call(body.querySelectorAll('.c-item'));
if (!items.length) return false;
var currentFull = null;
items.forEach(function (item) {
if (item.classList.contains('full')) {
currentFull = item;
} else if (item.classList.contains('reply') && currentFull) {
var targetContainer = currentFull.querySelector('.c-container');
if (targetContainer && item.parentElement !== targetContainer) {
targetContainer.appendChild(item);
item.classList.add('nested-in-parent');
}
}
});
body.dataset.repliesNested = '1';
return true;
}
Anachronism.waitFor(nestReplies);
})();
/* ============================================
隐藏 Special:ListGroupRights 里的"常客"行
(autoconfirmed 是核心隐式组,无法通过配置移除)
============================================ */
(function () {
var HIDE_GROUP_NAMES = ['常客'];
function hideRows() {
var table = document.querySelector('.mw-listgrouprights-table');
if (!table) return;
table.querySelectorAll('tr').forEach(function (tr) {
var link = tr.querySelector('a');
if (!link) return;
var text = (link.textContent || '').trim();
if (HIDE_GROUP_NAMES.indexOf(text) !== -1) {
tr.style.display = 'none';
}
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', hideRows);
} else {
hideRows();
}
})();
/* ============================================
特殊页面"相关页面"菜单:按有无图标加类
背景:Citizen 在 Special:Watchlist 等特殊页面上会渲染
#p-associated-pages 菜单。链接有的带图标,有的只有文字。
CSS 里若用 :has() 区分,部分解析器不识别会报错。
这里用 JS 预先打类,让 CSS 只需简单类选择器。
- .rail-has-icon → CSS 保持方块样式
- .rail-no-icon → CSS 改成文字按钮
============================================ */
(function () {
function markAssociatedPageButtons() {
var buttons = document.querySelectorAll('#p-associated-pages .mw-list-item > a');
if (!buttons.length) return false;
for (var i = 0; i < buttons.length; i++) {
var btn = buttons[i];
if (btn.dataset.railMarked === '1') continue;
btn.dataset.railMarked = '1';
if (btn.querySelector('.citizen-ui-icon')) {
btn.classList.add('rail-has-icon');
} else {
btn.classList.add('rail-no-icon');
}
}
return true;
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', function () {
Anachronism.waitFor(markAssociatedPageButtons, { timeoutMs: 5000 });
});
} else {
Anachronism.waitFor(markAssociatedPageButtons, { timeoutMs: 5000 });
}
})();
/* ============================================
站点头部:Logo + 站点名
在 .citizen-page-container 顶部插入一个独立 header,
位于主容器(.mw-body)之前。参照 Fandom 的社区头部做法。
数据来源:
- 站点名:mw.config 'wgSiteName'
- Logo 与首页 URL:优先从 Citizen 现有的 .mw-logo-icon
读取(Citizen header 被 CSS display:none 隐藏,DOM 仍在)。
兜底用 mw.config 'wgLogos' / 'wgLogo'。
============================================ */
(function () {
var HEADER_ID = 'site-header';
function buildHeader() {
if (document.getElementById(HEADER_ID)) return true;
var container = document.querySelector('.citizen-page-container');
if (!container) return false;
// 站点名
var siteName = mw.config.get('wgSiteName') || 'Anachronism';
// Logo 图片 URL 和首页链接
var logoUrl = '';
var homeUrl = '/';
var existingLogoImg = document.querySelector('.citizen-header__logo .mw-logo-icon')
|| document.querySelector('.mw-logo .mw-logo-icon')
|| document.querySelector('img.mw-logo-icon');
if (existingLogoImg) {
logoUrl = (existingLogoImg.getAttribute('src') || '').trim();
}
var existingLogoLink = document.querySelector('.citizen-header__logo a')
|| document.querySelector('a.mw-logo');
if (existingLogoLink) {
homeUrl = existingLogoLink.getAttribute('href') || homeUrl;
}
// 兜底:DOM 里找不到就查配置
if (!logoUrl) {
var logos = mw.config.get('wgLogos') || {};
logoUrl = logos['1x'] || logos['svg'] || mw.config.get('wgLogo') || '';
}
var logoImg = logoUrl
? '<img class="site-header__logo" src="' + logoUrl + '" alt="">'
: '';
var header = document.createElement('header');
header.id = HEADER_ID;
header.className = 'site-header';
header.innerHTML =
'<a class="site-header__brand" href="' + homeUrl + '">' +
logoImg +
'<span class="site-header__name">' + siteName + '</span>' +
'</a>';
container.insertBefore(header, container.firstChild);
return true;
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', function () {
Anachronism.waitFor(buildHeader, { timeoutMs: 5000 });
});
} else {
Anachronism.waitFor(buildHeader, { timeoutMs: 5000 });
}
})();
/* ============================================
右侧独立侧栏 + 展开/收起按钮
============================================ */
(function () {
var COLUMN_ID = 'anachronism-side-column';
var TOGGLE_ID = 'anachronism-aside-toggle';
var MIN_DESKTOP = 1101;
var GAP = 24; // 侧栏与 .mw-body 右边缘间距 (1.5rem)
var COL_W = 320; // 侧栏宽度 (20rem)
var EDGE = 8; // 侧栏与视口右边缘的最小间隙
function ensureSideColumn(mwBody) {
if (document.getElementById(COLUMN_ID)) return true;
var aside = mwBody.querySelector('.citizen-page-aside');
var footer = mwBody.querySelector('.citizen-page-footer');
if (!aside && !footer) return false;
var col = document.createElement('div');
col.id = COLUMN_ID;
col.className = 'anachronism-side-column';
if (aside) col.appendChild(aside);
if (footer) col.appendChild(footer);
mwBody.appendChild(col);
return true;
}
function ensureToggle(mwBody) {
if (document.getElementById(TOGGLE_ID)) return true;
var btn = document.createElement('button');
btn.id = TOGGLE_ID;
btn.type = 'button';
btn.className = 'anachronism-aside-toggle';
btn.setAttribute('aria-label', '展开/收起页面信息');
btn.setAttribute('title', '展开/收起页面信息');
btn.setAttribute('aria-expanded', 'false');
btn.innerHTML = '<span class="anachronism-aside-toggle__icon">▸</span>';
btn.addEventListener('click', function () {
var isOpen = document.body.classList.toggle('anachronism-aside-open');
btn.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
});
mwBody.appendChild(btn);
return true;
}
function reposition() {
if (window.innerWidth < MIN_DESKTOP) return;
var col = document.getElementById(COLUMN_ID);
var mwBody = document.querySelector('.mw-body');
if (!col || !mwBody) return;
var mwRect = mwBody.getBoundingClientRect();
var colLeft = Math.round(mwRect.right + GAP);
// 侧栏不能溢出视口右侧
var maxLeft = window.innerWidth - COL_W - EDGE;
if (colLeft > maxLeft) colLeft = maxLeft;
col.style.left = colLeft + 'px';
// top 由 CSS 固定 5rem
}
function start() {
var mwBody = document.querySelector('.mw-body');
if (!mwBody) return false;
if (!ensureSideColumn(mwBody)) return false;
if (!ensureToggle(mwBody)) return false;
// 默认展开
if (window.innerWidth >= MIN_DESKTOP) {
document.body.classList.add('anachronism-aside-open');
var btn = document.getElementById(TOGGLE_ID);
if (btn) btn.setAttribute('aria-expanded', 'true');
}
reposition();
window.addEventListener('resize', reposition);
new MutationObserver(reposition).observe(document.documentElement, {
attributes: true,
attributeFilter: ['class']
});
return true;
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', function () {
Anachronism.waitFor(start, { timeoutMs: 5000 });
});
} else {
Anachronism.waitFor(start, { timeoutMs: 5000 });
}
})();