1
Fork 0

Fix linting issues and move some things around.

This commit is contained in:
Bauke 2023-07-10 12:14:39 +02:00
parent 144c9c667b
commit 84c69eaab3
Signed by: Bauke
GPG Key ID: C1C0F29952BCF558
8 changed files with 64 additions and 44 deletions

View File

@ -1,12 +1,21 @@
import { log, querySelectorAll, getColorFromStringHash, isColorBright } from "../../utilities/exports.js"; import {type UsernameColorsData} from "../../storage/exports.js";
import { type UsernameColorsData } from "../../storage/exports.js"; import {
log,
querySelectorAll,
getColorFromStringHash,
isColorBright,
} from "../../utilities/exports.js";
export async function runUsernameColorsFeature( export async function runUsernameColorsFeature(
data: UsernameColorsData, data: UsernameColorsData,
anonymizeUsernamesEnabled: boolean, anonymizeUsernamesEnabled: boolean,
randomizeUsernameColorsEnabled: boolean, randomizeUsernameColorsEnabled: boolean,
) { ) {
const count = await usernameColors(data, anonymizeUsernamesEnabled, randomizeUsernameColorsEnabled); const count = await usernameColors(
data,
anonymizeUsernamesEnabled,
randomizeUsernameColorsEnabled,
);
log(`Username Colors: Applied ${count} colors.`); log(`Username Colors: Applied ${count} colors.`);
} }
@ -17,7 +26,7 @@ async function usernameColors(
): Promise<number> { ): Promise<number> {
const usernameColors = new Map<string, string>(); const usernameColors = new Map<string, string>();
for (const { for (const {
value: { color, username: usernames }, value: {color, username: usernames},
} of data) { } of data) {
for (const username of usernames.split(",")) { for (const username of usernames.split(",")) {
usernameColors.set(username.trim().toLowerCase(), color); usernameColors.set(username.trim().toLowerCase(), color);
@ -42,18 +51,21 @@ async function usernameColors(
} }
element.classList.add("trx-username-colors"); element.classList.add("trx-username-colors");
let color = usernameColors.get(target); const color = usernameColors.get(target);
if (color) { if (color !== undefined) {
element.style.color = color; element.style.color = color;
} else if (randomizeUsernameColorsEnabled) { } else if (randomizeUsernameColorsEnabled) {
element.classList.add("trx-random-username-color");
const randomColor = await getColorFromStringHash(target); const randomColor = await getColorFromStringHash(target);
const fontColor = isColorBright(randomColor) ? "#000" : "#FFF" const fontColor = isColorBright(randomColor) ? "#000" : "#FFF";
element.style.setProperty("--background-color", randomColor); element.style.setProperty("--background-color", randomColor);
element.style.setProperty("--text-color", fontColor); // Specifically use "--link-color" here so Tildes's link color doesn't
element.classList.add("trx-colored-username") // override ours.
element.style.setProperty("--link-color", fontColor);
} else { } else {
continue; continue;
} }
count += 1; count += 1;
} }

View File

@ -95,8 +95,14 @@ async function initialize() {
if (enabledFeatures.value.has(Feature.UsernameColors)) { if (enabledFeatures.value.has(Feature.UsernameColors)) {
observerFeatures.push(async () => { observerFeatures.push(async () => {
const data = await fromStorage(Feature.UsernameColors); const data = await fromStorage(Feature.UsernameColors);
const randomizeUsernameColors = await fromStorage(Data.RandomizeUsernameColors); const randomizeUsernameColors = await fromStorage(
runUsernameColorsFeature(data, anonymizeUsernamesEnabled, randomizeUsernameColors.value); Data.RandomizeUsernameColors,
);
await runUsernameColorsFeature(
data,
anonymizeUsernamesEnabled,
randomizeUsernameColors.value,
);
}); });
} }

View File

@ -1,3 +1,4 @@
import {type Value} from "@holllo/webextension-storage";
import {Component} from "preact"; import {Component} from "preact";
import {log} from "../../utilities/exports.js"; import {log} from "../../utilities/exports.js";
import { import {
@ -9,7 +10,6 @@ import {
fromStorage, fromStorage,
} from "../../storage/exports.js"; } from "../../storage/exports.js";
import {Setting, type SettingProps} from "./index.js"; import {Setting, type SettingProps} from "./index.js";
import { Value } from "@holllo/webextension-storage";
type State = { type State = {
previewChecked: "off" | "foreground" | "background"; previewChecked: "off" | "foreground" | "background";
@ -31,7 +31,10 @@ export class UsernameColorsSetting extends Component<SettingProps, State> {
} }
async componentDidMount() { async componentDidMount() {
this.setState({usernameColors: await fromStorage(Feature.UsernameColors), randomizeChecked: await fromStorage(Data.RandomizeUsernameColors)}); this.setState({
randomizeChecked: await fromStorage(Data.RandomizeUsernameColors),
usernameColors: await fromStorage(Feature.UsernameColors),
});
} }
addNewColor = async () => { addNewColor = async () => {
@ -104,12 +107,12 @@ export class UsernameColorsSetting extends Component<SettingProps, State> {
this.setState({previewChecked}); this.setState({previewChecked});
}; };
toggleRandomized = () => { toggleRandomized = async () => {
const randomizeChecked = this.state.randomizeChecked; const randomizeChecked = this.state.randomizeChecked;
randomizeChecked.value = !randomizeChecked.value; randomizeChecked.value = !randomizeChecked.value;
void randomizeChecked.save(); await randomizeChecked.save();
this.setState({randomizeChecked}) this.setState({randomizeChecked});
} };
onInput = (event: Event, id: number, key: "color" | "username") => { onInput = (event: Event, id: number, key: "color" | "username") => {
const colorIndex = this.state.usernameColors.findIndex( const colorIndex = this.state.usernameColors.findIndex(
@ -174,7 +177,6 @@ export class UsernameColorsSetting extends Component<SettingProps, State> {
); );
}); });
return ( return (
<Setting {...this.props}> <Setting {...this.props}>
<p class="info"> <p class="info">
@ -183,8 +185,9 @@ export class UsernameColorsSetting extends Component<SettingProps, State> {
You can enter multiple usernames separated by a comma if you want them You can enter multiple usernames separated by a comma if you want them
to use the same color. to use the same color.
<br /> <br />
If randomize is selected then all usernames will be given a random background color. If randomize is selected then all usernames will be given a random
This will not override colors you have manually assigned. background color. This will not override colors you have manually
assigned.
</p> </p>
<div class="username-colors-controls"> <div class="username-colors-controls">

View File

@ -2,10 +2,3 @@
/* stylelint-disable-next-line declaration-no-important */ /* stylelint-disable-next-line declaration-no-important */
display: none !important; display: none !important;
} }
.trx-colored-username {
background-color: var(--background-color);
border-radius: 3px;
color: var(--text-color);
padding: 2px 3px;
}

View File

@ -5,6 +5,7 @@
@import "scripts/jump-to-new-comment"; @import "scripts/jump-to-new-comment";
@import "scripts/markdown-toolbar"; @import "scripts/markdown-toolbar";
@import "scripts/user-labels"; @import "scripts/user-labels";
@import "scripts/username-colors";
// Miscellaneous // Miscellaneous
@import "shared"; @import "shared";

View File

@ -0,0 +1,6 @@
.trx-random-username-color {
background-color: var(--background-color);
border-radius: 3px;
color: var(--link-color);
padding: 2px 3px;
}

View File

@ -1,3 +1,12 @@
import {hashSha256} from "./text.js";
/** Return a hex color based on a hash of the input string. */
export async function getColorFromStringHash(input: string): Promise<string> {
const hash = Number.parseInt(await hashSha256(input), 16);
const color = Math.abs(hash % 0xff_ff_ff).toString(16);
return `#${color}`.padEnd(7, "0");
}
/** Returns whether a hex color is "bright". */ /** Returns whether a hex color is "bright". */
export function isColorBright(color: string): boolean { export function isColorBright(color: string): boolean {
if (color.startsWith("#")) { if (color.startsWith("#")) {

View File

@ -17,21 +17,11 @@ export function pluralize(
return plural ?? singular + "s"; return plural ?? singular + "s";
} }
/** Return a hash for a given username */ /** Return the SHA-256 hash for a given string. */
export async function hashString(str: string): Promise<string> { export async function hashSha256(input: string): Promise<string> {
const encoder = new TextEncoder(); const uint8Input = new window.TextEncoder().encode(input);
const data = encoder.encode(str) const digest = await window.crypto.subtle.digest("SHA-256", uint8Input);
const hashBuffer = await crypto.subtle.digest("SHA-256", data); return Array.from(new window.Uint8Array(digest))
const hashArray = Array.from(new Uint8Array(hashBuffer)); .map((byte) => byte.toString(16).padStart(2, "0"))
const hashString = hashArray
.map((b) => b.toString())
.join(""); .join("");
return hashString;
}
/** Return a color hex code based on hash of username string */
export async function getColorFromStringHash(username: string): Promise<string> {
const usernameHash = parseInt(await hashString(username));
const color = Math.abs(usernameHash % parseInt("0xFFFFFF")).toString(16)
return `#${color}`.padEnd(7, "0")
} }