All files / helpers colorHelpers.ts

100% Statements 39/39
100% Branches 16/16
100% Functions 3/3
100% Lines 39/39

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 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 401x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 3x 3x 1x 1x 5x 5x 5x 5x 3x 3x 5x 2x 2x 2x 1x 1x 5x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x  
import { type CSSProperties } from 'react';
 
import { AVAILABLE_COLOR_LIST } from './colorConstants';
 
export const hexToRgb = (
  hex: string | CSSProperties['color']
): number[] | null => {
  const match = hex
    ?.toString()
    .match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);
  if (!match) return null;
  return match.slice(1).map(x => parseInt(x, 16));
};
 
export const getContrastColor = (
  color: string | CSSProperties['color']
): 'var(--ft-color-lightest)' | 'var(--ft-color-darkest)' => {
  if (color === 'var(--ft-color-darkest)') return 'var(--ft-color-lightest)';
  if (color === 'var(--ft-color-lightest)') return 'var(--ft-color-darkest)';
 
  const rgb = hexToRgb(color);
  if (!rgb) return 'var(--ft-color-darkest)';
  const [r, g, b] = rgb;
  const brightness = (r * 299 + g * 587 + b * 114) / 1000;
  return brightness > 128
    ? 'var(--ft-color-darkest)'
    : 'var(--ft-color-lightest)';
};
 
export function getRandomColor(
  excludedColors?: CSSProperties['color'][]
): CSSProperties['color'] {
  const colors = AVAILABLE_COLOR_LIST.filter(
    color => !(excludedColors ?? []).includes(color)
  );
  const indexColor = Math.floor(Math.random() * colors.length);
  const color = colors[indexColor];
  return color;
}