1
Fork 0
tildes-reextended/source/content-scripts/features/username-colors.ts

74 lines
2.1 KiB
TypeScript
Raw Permalink Normal View History

import {type UsernameColorsData} from "../../storage/exports.js";
import {
log,
querySelectorAll,
getColorFromStringHash,
isColorBright,
} from "../../utilities/exports.js";
2023-06-23 10:52:03 +00:00
export async function runUsernameColorsFeature(
2023-06-23 10:52:03 +00:00
data: UsernameColorsData,
anonymizeUsernamesEnabled: boolean,
randomizeUsernameColorsEnabled: boolean,
2023-06-23 10:52:03 +00:00
) {
const count = await usernameColors(
data,
anonymizeUsernamesEnabled,
randomizeUsernameColorsEnabled,
);
2023-06-23 10:52:03 +00:00
log(`Username Colors: Applied ${count} colors.`);
}
async function usernameColors(
2023-06-23 10:52:03 +00:00
data: UsernameColorsData,
anonymizeUsernamesEnabled: boolean,
randomizeUsernameColorsEnabled: boolean,
): Promise<number> {
2023-06-23 10:52:03 +00:00
const usernameColors = new Map<string, string>();
for (const {
value: {color, username: usernames},
} of data) {
2023-06-23 10:52:03 +00:00
for (const username of usernames.split(",")) {
usernameColors.set(username.trim().toLowerCase(), color);
}
}
let count = 0;
const usernameElements = querySelectorAll<HTMLElement>(
".link-user:not(.trx-username-colors)",
);
for (const element of usernameElements) {
if (element.classList.contains("trx-username-colors")) {
continue;
}
let target =
element.textContent?.replace(/@/g, "").trim().toLowerCase() ??
"<unknown>";
if (anonymizeUsernamesEnabled) {
target = element.dataset.trxUsername?.toLowerCase() ?? target;
}
element.classList.add("trx-username-colors");
const color = usernameColors.get(target);
if (color !== undefined) {
element.style.color = color;
} else if (randomizeUsernameColorsEnabled) {
element.classList.add("trx-random-username-color");
const randomColor = await getColorFromStringHash(target);
const fontColor = isColorBright(randomColor) ? "#000" : "#FFF";
element.style.setProperty("--background-color", randomColor);
// Specifically use "--link-color" here so Tildes's link color doesn't
// override ours.
element.style.setProperty("--link-color", fontColor);
} else {
2023-06-23 10:52:03 +00:00
continue;
}
2023-06-23 10:52:03 +00:00
count += 1;
}
return count;
}