UNPKG

nhb-toolbox

Version:

A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.

46 lines (45 loc) 1.89 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.extractSolidColorValues = extractSolidColorValues; exports.extractAlphaColorValues = extractAlphaColorValues; exports.percentToHex = percentToHex; exports.applyOpacityToHex = applyOpacityToHex; const primitives_1 = require("../guards/primitives"); const guards_1 = require("./guards"); const helpers_1 = require("./helpers"); function extractSolidColorValues(color) { if ((0, guards_1.isHSL)(color) || (0, guards_1.isRGB)(color)) { return (color?.trim()?.match(/[\d.]+%?/g) || [])?.map((value) => parseFloat(value)); } return [0, 0, 0]; } function extractAlphaColorValues(color) { if ((0, guards_1.isHSLA)(color) || (0, guards_1.isRGBA)(color)) { return (color?.trim()?.match(/[\d.]+%?/g) || [])?.map((value) => parseFloat(value)); } return [0, 0, 0, 0]; } 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(); } function applyOpacityToHex(color, opacity) { if ((0, guards_1.isHex6)(color) || (0, guards_1.isHex8)(color)) { const upperColor = color.toUpperCase(); if ((0, primitives_1.isNumber)(opacity)) { return (0, helpers_1._applyOpacity)(upperColor, percentToHex(opacity)); } else if ((0, primitives_1.isNonEmptyString)(opacity) && /^[0-9A-Fa-f]{2}$/.test(opacity)) { return (0, helpers_1._applyOpacity)(upperColor, opacity.toUpperCase()); } else { return (0, helpers_1._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.', }); } }