get-contrast-text-color.ts
1 import hexToRgb from './hex-to-rgb'; 2 3 export default function getContrastColor(forColor: string): 'black' | 'white' { 4 const trimmed = forColor.trim(); 5 const isHex = trimmed.startsWith('#'); 6 7 let color: { r: number; g: number; b: number; a: number }; 8 9 if (isHex) { 10 const converted = hexToRgb(trimmed); 11 if (!converted) return 'white'; 12 13 color = { ...converted, a: 1 }; 14 } else { 15 const [r, g, b, a] = trimmed 16 .replace('rgba(', '') 17 .replace('rgb(', '') 18 .replace(')', '') 19 .split(',') 20 .map((v) => Number(v)); 21 22 color = { r, g, b, a }; 23 } 24 25 const { r, g, b, a } = color; 26 const brightness = r * 0.299 + g * 0.587 + b * 0.114 + (1 - a) * 255; 27 28 return brightness > 170 ? 'black' : 'white'; 29 }