Created
November 21, 2017 12:09
-
-
Save iremlopsum/d37c756083ba41ce0320d3d2d4777e99 to your computer and use it in GitHub Desktop.
hex to rgba mixin
This file contains 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
export default (property, hex, alpha, extraProperties) => { | |
const isHex = ((hex) => { | |
return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex) | |
}); | |
const hexToRGB = ((hex) => { | |
if (isHex(hex)) { | |
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; | |
const longHex = hex.replace(shorthandRegex, function(m, r, g, b) { | |
return r + r + g + g + b + b; | |
}); | |
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(longHex); | |
return result ? { | |
r: parseInt(result[1], 16), | |
g: parseInt(result[2], 16), | |
b: parseInt(result[3], 16) | |
} : null; | |
} else { | |
console.warn(`${hex} is not a valid hex value`) | |
} | |
}); | |
const rgb = hexToRGB(hex); | |
const rgba = `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${alpha})`; | |
const properyValue = extraProperties ? `${extraProperties} ${rgba}` : rgba; | |
const fullProperty = { | |
[property]: properyValue, | |
} | |
return fullProperty; | |
} | |
// Useage _hexToRGBA: ['backgroundColor', '$deepBlue100', '.3'], |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment