aboutsummaryrefslogtreecommitdiff
path: root/src/lib/color.ts
blob: 59b320d57fc1dbbf08cc88126b062625c3421f8c (plain)
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
interface Color {
  red: number,
  green: number,
  blue: number,
}

export function parse(str: string): Color {
  return {
    red: parseInt(str.slice(1,3), 16),
    green: parseInt(str.slice(3,5), 16),
    blue: parseInt(str.slice(5,7), 16),
  }
}

// https://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrastratio
export function contrastRatio(c1: Color, c2: Color): number {
  const r1 = relativeLuminance(c1)
  const r2 = relativeLuminance(c2)

  return r1 > r2
    ? (r1 + 0.05) / (r2 + 0.05)
    : (r2 + 0.05) / (r1 + 0.05)
}

function relativeLuminance(c: Color): number {
  return (
    0.2126 * fromSRGB(c.red / 255) 
    + 0.7152 * fromSRGB(c.green / 255) 
    + 0.0722 * fromSRGB(c.blue / 255))
}

function fromSRGB(sRGB: number): number {
  return sRGB <= 0.03928
    ? sRGB / 12.92
    : Math.pow(((sRGB + 0.055) / 1.055), 2.4)
}