Skip to content

Instantly share code, notes, and snippets.

@chadlavi
Created Sep 13, 2020
Embed
What would you like to do?
bash function wrapper around a node script to check color contrast.
# calculate the WCAG contrast ratio between a single hex color and white, or
# between two hex color values
contrast () {
if [ -x "$(command -v node)" ]; then
node -e "function hexToRgb(hex) {
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(
shorthandRegex,
(_m, r, g, b) => r + r + g + g + b + b
);
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
}
: undefined;
}
function luminance(r, g, b) {
const a = [r, g, b].map((v) => {
v /= 255;
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
});
return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722;
}
const contrast = (c1, c2 = 'ffffff') => {
if (!c1.match(/^[a-fA-F0-9]{6}$/)) console.log('First number not a hex color value')
if (!c2.match(/^[a-fA-F0-9]{6}$/)) console.log('Second number not a hex color value')
const rgb1 = hexToRgb(c1);
const rgb2 = hexToRgb(c2);
if (rgb1 && rgb2) {
const c1luminance = luminance(rgb1.r, rgb1.g, rgb1.b);
const c2luminance = luminance(rgb2.r, rgb2.g, rgb2.b);
const ratio =
c1luminance > c2luminance
? (c2luminance + 0.05) / (c1luminance + 0.05)
: (c1luminance + 0.05) / (c2luminance + 0.05);
return parseFloat((1 / ratio).toFixed(2));
}
};
console.log(contrast('$1', '${2:-ffffff}') || '');
"
else
echo "Node not installed"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment