commented color.ts file

This commit is contained in:
waltem01 2022-08-07 19:02:13 +02:00
parent d36f05a3d0
commit d3016684f3

View File

@ -1,16 +1,20 @@
// Interface to represent color objects
export interface Color { export interface Color {
r: number; r: number;
g: number; g: number;
b: number; b: number;
} }
// Get black or white hex color depending on contrast (luminance)
export function getContrastColor(hexColor: string): string { export function getContrastColor(hexColor: string): string {
const rgb = hexToRgb(hexColor); const rgb = hexToRgb(hexColor);
const luminance = getLuminance(rgb ?? ({ r: 0, g: 0, b: 0 } as Color)); const luminance = getLuminance(rgb ?? ({ r: 0, g: 0, b: 0 } as Color));
return luminance > 0.5 ? '000000' : 'FFFFFF'; return luminance > 0.5 ? '000000' : 'FFFFFF';
} }
// Convert hex color to rgb color object
export function hexToRgb(hex: string): Color | null { export function hexToRgb(hex: string): Color | null {
// Split string everz two characters, extract hex rgb values
const result = /^([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); const result = /^([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result return result
? { ? {
@ -21,6 +25,7 @@ export function hexToRgb(hex: string): Color | null {
: null; : null;
} }
// Get luminance value from rgb values of a color as defined by the Web Content Accessibility Guidelines (WCAG)
export function getLuminance(rgb: Color): number { export function getLuminance(rgb: Color): number {
const a = [rgb.r, rgb.g, rgb.b].map((v) => { const a = [rgb.r, rgb.g, rgb.b].map((v) => {
v /= 255; v /= 255;
@ -29,8 +34,9 @@ export function getLuminance(rgb: Color): number {
return 0.2126 * a[0] + 0.7152 * a[1] + 0.0722 * a[2]; return 0.2126 * a[0] + 0.7152 * a[1] + 0.0722 * a[2];
} }
// Convert an rgb color object to a hex color string
export function rgbToHex(color: Color): string { export function rgbToHex(color: Color): string {
return (Object.entries(color) as [string, number][]) return [color.r, color.g, color.b]
.map((e) => e[1].toString(16).padStart(2, '0')) .map((e) => e.toString(16).padStart(2, '0'))
.join(''); .join('');
} }