nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.
40 lines (39 loc) • 1.53 kB
JavaScript
import { isNonEmptyString, isNumber } from '../guards/primitives.js';
import { isHex6, isHex8, isHSL, isHSLA, isRGB, isRGBA } from './guards.js';
import { _applyOpacity } from './helpers.js';
export function extractSolidColorValues(color) {
if (isHSL(color) || isRGB(color)) {
return (color?.trim()?.match(/[\d.]+%?/g) || [])?.map((value) => parseFloat(value));
}
return [0, 0, 0];
}
export function extractAlphaColorValues(color) {
if (isHSLA(color) || isRGBA(color)) {
return (color?.trim()?.match(/[\d.]+%?/g) || [])?.map((value) => parseFloat(value));
}
return [0, 0, 0, 0];
}
export function percentToHex(percent) {
const validOpacity = Math.min(100, Math.max(0, percent));
const alpha = Math.round((validOpacity / 100) * 255);
return alpha.toString(16).padStart(2, '0').toUpperCase();
}
export function applyOpacityToHex(color, opacity) {
if (isHex6(color) || isHex8(color)) {
const upperColor = color.toUpperCase();
if (isNumber(opacity)) {
return _applyOpacity(upperColor, percentToHex(opacity));
}
else if (isNonEmptyString(opacity) && /^[0-9A-Fa-f]{2}$/.test(opacity)) {
return _applyOpacity(upperColor, opacity.toUpperCase());
}
else {
return _applyOpacity(upperColor, percentToHex(100));
}
}
else {
throw new TypeError('Invalid color value!', {
cause: 'Value must be a hex color string in the format #RRGGBB or #RRGGBBAA.',
});
}
}