@@ -23,6 +23,34 @@ const hexToRgb = (
2323 : null ;
2424} ;
2525
26+ // https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
27+ // Based on: https://github.com/siege-media/contrast-ratio/blob/gh-pages/color.js
28+ const processLuminance = ( channel : number ) : number => {
29+ const scaledChannel = channel / 255 ;
30+ return scaledChannel <= 0.03928
31+ ? scaledChannel / 12.92
32+ : Math . pow ( ( scaledChannel + 0.055 ) / 1.055 , 2.4 ) ;
33+ } ;
34+
35+ const getLuminance = ( colour : string ) : number => {
36+ const rgb = hexToRgb ( colour ) ;
37+ if ( ! rgb ) return 0 ;
38+ return (
39+ processLuminance ( rgb . r ) * 0.2126 +
40+ processLuminance ( rgb . g ) * 0.7152 +
41+ processLuminance ( rgb . b ) * 0.0722
42+ ) ;
43+ } ;
44+
45+ // http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef
46+ export const getContrast = ( colour1 : string , colour2 : string ) : number => {
47+ const luminance1 = getLuminance ( colour1 ) ;
48+ const luminance2 = getLuminance ( colour2 ) ;
49+ const brightest = Math . max ( luminance1 , luminance2 ) ;
50+ const darkest = Math . min ( luminance1 , luminance2 ) ;
51+ return ( brightest + 0.05 ) / ( darkest + 0.05 ) ;
52+ } ;
53+
2654const getBrightness = ( colour : string ) : number => {
2755 // http://www.w3.org/TR/AERT#color-contrast
2856 const rgb = hexToRgb ( colour ) ;
0 commit comments