@onesy/utils
Version:
23 lines (22 loc) • 1.45 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const is_1 = __importDefault(require("./is"));
const isValid_1 = __importDefault(require("./isValid"));
const clamp_1 = __importDefault(require("./clamp"));
const castParam_1 = __importDefault(require("./castParam"));
const hexToRgb = (value, opacity = undefined, array = false) => {
if ((0, isValid_1.default)('color-hex', value)) {
const hex = value.slice(1);
let r = parseInt(hex.length === 3 ? `${hex[0]}${hex[0]}` : hex.slice(0, 2), 16);
let g = parseInt(hex.length === 3 ? `${hex[1]}${hex[1]}` : hex.slice(2, 4), 16);
let b = parseInt(hex.length === 3 ? `${hex[2]}${hex[2]}` : hex.slice(4, 6), 16);
let a = opacity !== undefined ? opacity > 1 ? (opacity / 100).toFixed(2) : (0, clamp_1.default)(opacity, 0, 1) : (hex.length === 8) && (parseInt(hex.slice(6), 16) / 255).toFixed(2);
const values = [...[r, g, b].map(item => Math.round((0, castParam_1.default)(item))), (0, is_1.default)('number', a) && +a];
[r, g, b, a] = values;
return array ? values.filter(value_ => (0, is_1.default)('number', value_)) : `rgb${(0, is_1.default)('number', a) ? 'a' : ''}(${r}, ${g}, ${b}${(0, is_1.default)('number', a) ? `, ${a}` : ''})`;
}
};
exports.default = hexToRgb;
;