apphouse
Version:
Component library for React that uses observable state management and theme-able components.
47 lines (39 loc) • 1.17 kB
text/typescript
// Checks if a string is a valid HSLA color.
export function isHslaColor(color: string): boolean {
// Check if the color starts with 'hsla(' and ends with ')'
if (!color.startsWith('hsla(') || !color.endsWith(')')) {
return false;
}
// Remove 'hsla(' and ')' from the color string
const hsla = color.slice(5, -1);
// Split the color string by commas
const values = hsla.split(',');
// Check if the color has exactly 4 values
if (values.length !== 4) {
return false;
}
// Check if each value is a valid number within the appropriate range
const hue = Number(values[0].trim());
const saturation = Number(values[1].trim());
const lightness = Number(values[2].trim());
const alpha = Number(values[3].trim());
// Check range for HSL values: hue, saturation, lightness
if (
isNaN(hue) ||
hue < 0 ||
hue > 360 ||
isNaN(saturation) ||
saturation < 0 ||
saturation > 100 ||
isNaN(lightness) ||
lightness < 0 ||
lightness > 100
) {
return false;
}
// Check range for alpha value: between 0 and 1
if (isNaN(alpha) || alpha < 0 || alpha > 1) {
return false;
}
return true;
}