hex-to-css-filter
Version:
hex-to-css-filter - Easy way to generate colors from HEX to CSS Filters
74 lines (73 loc) • 2.35 kB
JavaScript
import { Solver } from './solver';
import { Color } from './color';
/**
* Transform a CSS Color from Hexadecimal to RGB color
*
* @param {string} hex hexadecimal color
* @returns {([number, number, number] | [])} array with the RGB colors or empty array
*/
const hexToRgb = (hex) => {
if (hex.length === 4) {
return [parseInt(`0x${hex[1]}${hex[1]}`), parseInt(`0x${hex[2]}${hex[2]}`), parseInt(`0x${hex[3]}${hex[3]}`)];
}
if (hex.length === 7) {
return [parseInt(`0x${hex[1]}${hex[2]}`), parseInt(`0x${hex[3]}${hex[4]}`), parseInt(`0x${hex[5]}${hex[6]}`)];
}
return [];
};
const isNumeric = (n) => !isNaN(parseFloat(n)) && isFinite(n);
// Memory cache for the computed results to avoid multiple
// calculations for the same color
let results = {};
/**
* A function that transforms a HEX color into CSS filters
*
* @param colorValue string hexadecimal color
* @param opts HexToCssConfiguration function configuration
*
*/
export const hexToCSSFilter = (colorValue, opts = {}) => {
let red;
let green;
let blue;
if (results[colorValue] && !opts.forceFilterRecalculation) {
return Object.assign({}, results[colorValue], { cache: true });
}
let color;
try {
[red, green, blue] = hexToRgb(colorValue);
if (!isNumeric(red) || !isNumeric(green) || !isNumeric(blue)) {
throw new Error(`hextToRgb returned an invalid value for '${colorValue}'`);
}
color = new Color(Number(red), Number(green), Number(blue));
}
catch (error) {
throw new Error(`Color value should be in HEX format. ${error}`);
}
const solver = new Solver(color, Object.assign({},
// `HexToCssConfiguration` Defaults
{
acceptanceLossPercentage: 5,
maxChecks: 30,
forceFilterRecalculation: false,
}, opts));
return (results[colorValue] = Object.assign({}, solver.solve(), {
hex: colorValue,
rgb: [red, green, blue],
cache: false,
}));
};
/**
* A function that clears cached results
*
* @param {string} key? HEX string value passed previously `#24639C`. If not passed, it clears all cached results
* @returns void
*/
export const clearCache = (key) => {
if (!key) {
results = {};
}
else if (results[key]) {
delete results[key];
}
};