UNPKG

@amaui/utils

Version:
33 lines (26 loc) 1.34 kB
import is from './is'; import isValid from './isValid'; import castParam from './castParam'; import clamp from './clamp'; const hslToRgb = function (value) { let opacity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; let array = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (isValid('color-hsl', value)) { let values = value.replace(/hsl|a|\(|%|\s|\)/g, '').split(','); let [h, s, l, a] = [...values.slice(0, 3).map(item => +castParam(item).toFixed(0)), values[3]]; h = parseInt(h, 10); s = parseInt(s, 10) / 100; l = parseInt(l, 10) / 100; a = opacity !== undefined ? opacity > 1 ? (opacity / 100).toFixed(2) : clamp(opacity, 0, 1) : parseFloat(a); const k = n => (n + h / 30) % 12; const u = s * Math.min(l, 1 - l); const f = n => l - u * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1))); let r = 255 * f(0); let g = 255 * f(8); let b = 255 * f(4); values = [...[r, g, b].map(item => Math.round(castParam(item))), is('number', a) && +a]; [r, g, b, a] = values; return array ? values.filter(value_ => is('number', value_)) : "rgb".concat(is('number', a) ? 'a' : '', "(").concat(r, ", ").concat(g, ", ").concat(b).concat(is('number', a) ? ", ".concat(a) : '', ")"); } }; export default hslToRgb;