1+ import { getLuminance } from 'polished' ;
2+
13const RGB_HEX = / ^ # ? (?: ( [ \d a - f ] { 3 } ) [ \d a - f ] ? | ( [ \d a - f ] { 6 } ) (?: [ \d a - f ] { 2 } ) ? ) $ / i;
24
35/** Ensure the consistency of colors between old and new colors */
@@ -45,23 +47,9 @@ export const hex2RGB = (str: string): [number, number, number] => {
4547 throw new Error ( 'Invalid hex string provided' ) ;
4648} ;
4749
48- // WCAG 2.0 relative luminance
49- const relativeLuminance = ( r : number , g : number , b : number ) : number => {
50- const [ rs , gs , bs ] = [ r , g , b ] . map ( ( c ) => {
51- const s = c / 255 ;
52- return s <= 0.03928 ? s / 12.92 : ( ( s + 0.055 ) / 1.055 ) ** 2.4 ;
53- } ) ;
54- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs ;
55- } ;
56-
5750const wcagContrastRatio = ( l1 : number , l2 : number ) : number =>
5851 ( Math . max ( l1 , l2 ) + 0.05 ) / ( Math . min ( l1 , l2 ) + 0.05 ) ;
5952
60- const luminanceOf = ( hex : string ) : number => {
61- const [ r , g , b ] = hex2RGB ( hex ) ;
62- return relativeLuminance ( r , g , b ) ;
63- } ;
64-
6553// Minimum WCAG contrast ratio to consider a text color readable on a background.
6654// 3.0 corresponds to WCAG AA for large text — same threshold used by MUI.
6755const CONTRAST_THRESHOLD = 3 ;
@@ -72,9 +60,9 @@ export const getContrastText = (
7260 textReverse : string ,
7361) : string | null => {
7462 try {
75- const bgLum = luminanceOf ( bgColor ) ;
76- const primaryLum = luminanceOf ( textPrimary ) ;
77- const reverseLum = luminanceOf ( textReverse ) ;
63+ const bgLum = getLuminance ( bgColor ) ;
64+ const primaryLum = getLuminance ( textPrimary ) ;
65+ const reverseLum = getLuminance ( textReverse ) ;
7866
7967 const lighterText = primaryLum >= reverseLum ? textPrimary : textReverse ;
8068 const darkerText = primaryLum >= reverseLum ? textReverse : textPrimary ;
0 commit comments