kute.js/src/util/trueColor.js
thednp 2a5bac2bb3 Changes V2.2.0:
* major JSDoc write up
* removed ESLint `no-bitwise` exception, it only applies to specific functions and not the entire code
* the `SVGCubicMorph` component will remove un-necessary `Z` path commands when is the case for better out of the box animation
* fixed a minor disambiguation with `filterEffects` and `drop-shadow` property and its `dropshadow` interpolation function
* TypeScript strong: all files are modules, easy to implement in any third party app
* updated `CubicBezier` and SVGPathCommander
* code cleanup
2021-12-08 23:43:31 +02:00

50 lines
1.6 KiB
JavaScript

import hexToRGB from './hexToRGB';
/**
* trueColor
*
* Transform any color to rgba()/rgb() and return a nice RGB(a) object.
*
* @param {string} colorString the color input
* @returns {KUTE.colorObject} the {r,g,b,a} color object
*/
const trueColor = (colorString) => {
let result;
if (/rgb|rgba/.test(colorString)) { // first check if it's a rgb string
const vrgb = colorString.replace(/\s|\)/, '').split('(')[1].split(',');
const colorAlpha = vrgb[3] ? vrgb[3] : null;
if (!colorAlpha) {
result = { r: parseInt(vrgb[0], 10), g: parseInt(vrgb[1], 10), b: parseInt(vrgb[2], 10) };
}
result = {
r: parseInt(vrgb[0], 10),
g: parseInt(vrgb[1], 10),
b: parseInt(vrgb[2], 10),
a: parseFloat(colorAlpha),
};
} if (/^#/.test(colorString)) {
const fromHex = hexToRGB(colorString);
result = { r: fromHex.r, g: fromHex.g, b: fromHex.b };
} if (/transparent|none|initial|inherit/.test(colorString)) {
result = {
r: 0, g: 0, b: 0, a: 0,
};
}
// maybe we can check for web safe colors
// only works in a browser
if (!/^#|^rgb/.test(colorString)) {
const siteHead = document.getElementsByTagName('head')[0];
siteHead.style.color = colorString;
let webColor = getComputedStyle(siteHead, null).color;
webColor = /rgb/.test(webColor) ? webColor.replace(/[^\d,]/g, '').split(',') : [0, 0, 0];
siteHead.style.color = '';
result = {
r: parseInt(webColor[0], 10),
g: parseInt(webColor[1], 10),
b: parseInt(webColor[2], 10),
};
}
return result;
};
export default trueColor;