All files / src/utils color.ts

100% Statements 11/11
100% Branches 6/6
100% Functions 2/2
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21          43x 43x   41x 41x 41x 41x   41x 123x   41x   41x    
/**
 * Picks black or white text for readability against a given background color,
 * using the WCAG relative luminance formula.
 */
export function getContrastTextColor(hexColor: string): string {
  const match = /^#([0-9a-f]{6})$/i.exec(hexColor)
  if (!match) return '#000000'
 
  const value = match[1] as string
  const r = parseInt(value.substring(0, 2), 16) / 255
  const g = parseInt(value.substring(2, 4), 16) / 255
  const b = parseInt(value.substring(4, 6), 16) / 255
 
  const [rl, gl, bl] = [r, g, b].map((c) =>
    c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4)
  )
  const luminance = 0.2126 * rl! + 0.7152 * gl! + 0.0722 * bl!
 
  return luminance > 0.5 ? '#000000' : '#ffffff'
}