/** Whether a value is a whole `#rrggbb` colour, as the colour fields hold it. */
export function isHexColour(value: string): boolean {
  return /^#[0-9a-fA-F]{6}$/.test(value);
}

function relativeLuminance(hex: string): number {
  const [r, g, b] = [1, 3, 5].map((at) => {
    const channel = parseInt(hex.slice(at, at + 2), 16) / 255;
    return channel <= 0.03928
      ? channel / 12.92
      : Math.pow((channel + 0.055) / 1.055, 2.4);
  });
  return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}

/** The least contrast WCAG AA asks between an icon and its ground. */
export const MIN_ICON_CONTRAST = 4.5;

/**
 * The WCAG contrast ratio between two `#rrggbb` colours, from 1 to 21, or
 * null while one of them is not whole (a colour being typed).
 */
export function contrastRatio(one: string, other: string): number | null {
  if (!isHexColour(one) || !isHexColour(other)) return null;
  const a = relativeLuminance(one);
  const b = relativeLuminance(other);
  return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
}
