apphouse
Version:
Component library for React that uses observable state management and theme-able components.
78 lines (76 loc) • 2.68 kB
text/typescript
import { isHslColor } from './isHslColor';
import { isHslaColor } from './isHslaColor';
import { isRgbColor } from './isRgbColor';
import { isRgbaColor } from './isRgbaColor';
/**
* Converts a valid RGB, RGBA, HSL, or HSLA color string to a hex color string.
* @param {string} value - The color string to convert.
* @returns {string} Returns the hex color string if conversion succeeds, otherwise an empty string.
*/
export function toHex(value: string): string {
//@ts-ignore
let alpha = 1;
if (isRgbColor(value)) {
// If the input value is a valid RGB color, convert it to hex using regular expressions
const rgbValues = value.match(/\d+/g);
if (rgbValues) {
const hexValues = rgbValues.map((val, index) => {
if (index === 3) {
alpha = parseFloat(val) / 255;
return '';
}
return parseInt(val).toString(16).padStart(2, '0');
});
return `#${hexValues.join('')}`;
}
} else if (isRgbaColor(value)) {
// If the input value is a valid RGBA color, convert it to hex using regular expressions
const rgbaValues = value.match(/\d+/g);
if (rgbaValues) {
const hexValues = rgbaValues.map((val, index) => {
if (index === 3) {
alpha = parseFloat(val);
return '';
}
return parseInt(val).toString(16).padStart(2, '0');
});
return `#${hexValues.join('')}`;
}
} else if (isHslColor(value)) {
// If the input value is a valid HSL color, convert it to hex using a temporary element
const div = document.createElement('div');
div.style.color = value;
const computedColor = window.getComputedStyle(div).color;
const hexValue = computedColor.match(/\d+/g)?.reduce((acc, val, index) => {
if (index === 3) {
alpha = parseFloat(val) / 255;
return acc;
}
return (
acc + (index === 0 ? '' : parseInt(val).toString(16).padStart(2, '0'))
);
}, '#');
if (hexValue) {
return hexValue;
}
} else if (isHslaColor(value)) {
// If the input value is a valid HSLA color, convert it to hex using a temporary element
const div = document.createElement('div');
div.style.color = value;
const computedColor = window.getComputedStyle(div).color;
const hexValue = computedColor.match(/\d+/g)?.reduce((acc, val, index) => {
if (index === 3) {
alpha = parseFloat(val);
return acc;
}
return (
acc + (index === 0 ? '' : parseInt(val).toString(16).padStart(2, '0'))
);
}, '#');
if (hexValue) {
return hexValue;
}
}
// Return an empty string if conversion fails
return '';
}