Last active
January 12, 2018 23:24
-
-
Save Danetag/ddaf98f917d02accd07e47da544c4565 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import tinycolor from 'tinycolor2'; | |
| import VARS from 'base/vars'; | |
| // https://www.w3.org/TR/WCAG20/#contrast-ratiodef | |
| export const CONTRAST_RATIO = 3.1; | |
| /* | |
| * @name getValidColor | |
| * @description Returns a color that satisfies that contrast color check between a background color and a text color. | |
| * @param backgroundColor {string} Hexadecimal value of the background color | |
| * @param color {string} Hexadecimal value of the (text) color you want to check | |
| * @param lightColorDefault {string} Hexadecimal value of the light default color if the check fails and it's too dark | |
| * @param darkColorDefault {string} Hexadecimal value of the dark default color if the check fails and it's too light | |
| * @return {string} Hexadecimal value | |
| */ | |
| export const getValidColor = (backgroundColor, color, lightColorDefault = VARS['white'], darkColorDefault = VARS['main-text-color']) => { | |
| const B1 = tinycolor(backgroundColor).getBrightness(); | |
| const B2 = tinycolor(color).getBrightness(); | |
| const L1 = tinycolor(backgroundColor).getLuminance(); | |
| const L2 = tinycolor(color).getLuminance(); | |
| const ratio = Math.round((Math.max(L1, L2) + 0.05) / (Math.min(L1, L2) + 0.05) * 10) / 10; | |
| // Nothing has to be changed | |
| if (ratio > CONTRAST_RATIO) { | |
| return color; | |
| } | |
| // If too dark, return the light default color | |
| if (B1 < 127 && B2 < 127) { | |
| return lightColorDefault; | |
| } | |
| // If too light, return the dark default color | |
| if (B1 > 127 && B2 > 127) { | |
| return darkColorDefault; | |
| } | |
| return color; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment