@onesy/utils
Version:
45 lines (44 loc) • 1.92 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 rgbToHsl = (value, opacity = undefined, array = false) => {
if ((0, isValid_1.default)('color-rgb', value)) {
let values = value.replace(/rgb|a|\(|\s|\)/g, '').split(',').filter(Boolean);
let [r, g, b, a] = values;
r /= 255;
g /= 255;
b /= 255;
// find greatest and smallest channel values
const cmin = Math.min(r, g, b);
const cmax = Math.max(r, g, b);
const delta = cmax - cmin;
let h = 0;
let s = 0;
let l = 0;
if (delta === 0)
h = 0;
else if (cmax === r)
h = ((g - b) / delta) % 6;
else if (cmax === g)
h = (b - r) / delta + 2;
else
h = (r - g) / delta + 4;
h = Math.round(h * 60);
if (h < 0)
h += 360;
l = (cmax + cmin) / 2;
s = delta === 0 ? 0 : delta / (1 - Math.abs(2 * l - 1));
s = +(s * 100).toFixed(0);
l = +(l * 100).toFixed(0);
a = opacity !== undefined ? +(opacity > 1 ? (opacity / 100).toFixed(2) : (0, clamp_1.default)(opacity, 0, 1)) : a;
values = [...[h, s, l].map(value_ => Math.round((0, castParam_1.default)(value_))), (0, is_1.default)('number', a) && +a];
return array ? values.filter(value_ => (0, is_1.default)('number', value_)) : `hsl${(0, is_1.default)('number', a) ? 'a' : ''}(${h}, ${s}%, ${l}%${(0, is_1.default)('number', a) ? `, ${a}` : ''})`;
}
};
exports.default = rgbToHsl;