Make text of light tags legible

This commit is contained in:
Roy-Orbison
2022-01-05 17:36:01 +10:30
committed by Alejandro Celaya
parent 5b7f1ef18a
commit 1e03eed6c0
3 changed files with 22 additions and 2 deletions

View File

@@ -2,16 +2,21 @@ import { rangeOf } from '../utils';
import LocalStorage from './LocalStorage';
const HEX_COLOR_LENGTH = 6;
const { floor, random } = Math;
const { floor, random, sqrt, round } = Math;
const letters = '0123456789ABCDEF';
const buildRandomColor = () => `#${rangeOf(HEX_COLOR_LENGTH, () => letters[floor(random() * letters.length)]).join('')}`;
const normalizeKey = (key: string) => key.toLowerCase().trim();
const hexColorToRgbArray = (colorHex: string): number[] => (colorHex.match(/../g) || []).map(hex => parseInt(hex, 16) || 0);
// HSP by Darel Rex Finley https://alienryderflex.com/hsp.html
const perceivedLightness = (r: number = 0, g: number = 0, b: number = 0) => round(sqrt(0.299 * r ** 2 + 0.587 * g ** 2 + 0.114 * b ** 2));
export default class ColorGenerator {
private readonly colors: Record<string, string>;
private readonly lights: Record<string, boolean>;
public constructor(private readonly storage: LocalStorage) {
this.colors = this.storage.get<Record<string, string>>('colors') ?? {};
this.lights = {};
}
public readonly getColorForKey = (key: string) => {
@@ -34,4 +39,15 @@ export default class ColorGenerator {
return color;
};
public readonly isColorLightForKey = (key: string) => {
const colorHex = this.getColorForKey(key).substring(1);
if (this.lights[colorHex] == undefined) {
const rgb = hexColorToRgbArray(colorHex);
this.lights[colorHex] = perceivedLightness(...rgb) >= 128;
}
return this.lights[colorHex];
};
}