1
Fork 0
tildes-reextended/source/content-scripts/features/anonymize-usernames.ts

47 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-06-23 10:52:03 +00:00
import {log, querySelectorAll} from "../../utilities/exports.js";
export function runAnonymizeUsernamesFeature() {
const count = anonymizeUsernames();
log(`Anonymize Usernames: Initialized for ${count} user links.`);
}
function anonymizeUsernames(): number {
const usernameElements = querySelectorAll<HTMLElement>(
2023-06-23 10:52:03 +00:00
".link-user:not(.trx-anonymized)",
);
const replacements = generateReplacements(usernameElements);
for (const element of usernameElements) {
let username = usernameFromElement(element);
2023-06-23 10:52:03 +00:00
const isMention = username.startsWith("@");
if (isMention) {
username = username.slice(1);
}
const replacement = replacements[username];
element.textContent = isMention ? `@${replacement}` : `${replacement}`;
2023-06-23 10:52:03 +00:00
element.classList.add("trx-anonymized");
element.dataset.trxUsername = username;
}
return usernameElements.length;
}
function generateReplacements(elements: HTMLElement[]): Record<string, string> {
const usernames = new Set(
2023-06-23 10:52:03 +00:00
elements.map((element) => usernameFromElement(element).replace(/@/g, "")),
);
const replacements: Record<string, string> = {};
for (const [index, username] of Array.from(usernames).entries()) {
replacements[username] = `Anonymous ${index + 1}`;
}
return replacements;
}
function usernameFromElement(element: HTMLElement): string {
return (element.textContent ?? "<unknown>").trim().toLowerCase();
}