@onesy/utils
Version:
28 lines (27 loc) • 1.32 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const isValid_1 = __importDefault(require("./isValid"));
const clamp_1 = __importDefault(require("./clamp"));
const castParam_1 = __importDefault(require("./castParam"));
const intToHex = (value) => {
const hex = (0, castParam_1.default)(value).toString(16);
return hex.length === 1 ? `0${hex}` : hex;
};
const rgbToHex = (value, opacity_ = undefined, array = false) => {
if ((0, isValid_1.default)('color-rgb', value)) {
let values = value.replace(/rgb|a|\(|\s|\)/g, '').split(',').filter(Boolean);
// If alpha value exists, multiply it by 255 rgb max range value
if (values[3])
values[3] = Math.round(parseFloat(values[3]) * 255);
const opacity = opacity_ !== undefined && (opacity_ > 1 ? +(opacity_ / 100).toFixed(2) : (0, clamp_1.default)(opacity_, 0, 1));
if (opacity)
values.push(Math.round(parseFloat(opacity) * 255));
values = values.map(item => intToHex(item));
const [r, g, b, a] = values;
return array ? values.filter(Boolean) : `#${r}${g}${b}${a ? a : ''}`;
}
};
exports.default = rgbToHex;
;