Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const [r, g, b] = lab2rgb(lightness, 0, 0).map(
channel => Math.max(Math.min(Math.round(channel * 2.55), 255), 0)
);
// preserve the slash nodes within rgb()
const openingSlash = node.first;
const closingSlash = node.last;
node.removeAll()
// replace the contents of rgb with `(r,g,b`
.append(openingSlash)
.append(parser.number({ value: r }))
.append(parser.comma({ value: ',' }))
.append(parser.number({ value: g }))
.append(parser.comma({ value: ',' }))
.append(parser.number({ value: b }))
// if an alpha channel was defined
if (alpha < 1) {
// rename the rgb() function to rgba()
node.value += 'a';
node
// append the contents of rgba with `,a`
.append(parser.comma({ value: ',' }))
.append(parser.number({ value: alpha }));
}
// append the contents of rgb/rgba with `)`
node.append(closingSlash);
}
});
// conditionally expand a hex
const hex8 = `0x${hex.length === 5 ? hex.slice(1).replace(/[0-9A-f]/g, '$&$&') : hex.slice(1)}`;
// extract the red, blue, green, and alpha values from the hex
const [r, g, b, a] = [
parseInt(hex8.slice(2, 4), 16),
parseInt(hex8.slice(4, 6), 16),
parseInt(hex8.slice(6, 8), 16),
Math.round(parseInt(hex8.slice(8, 10), 16) / 255 * alphaDecimalPrecision) / alphaDecimalPrecision
];
// return a new rgba function, preserving the whitespace of the original node
const rgbaFunc = valueParser.func({ value: 'rgba', raws: Object.assign({}, node.raws) });
rgbaFunc.append(valueParser.paren({ value: '(' }));
rgbaFunc.append(valueParser.number({ value: r }));
rgbaFunc.append(valueParser.comma({ value: ',' }));
rgbaFunc.append(valueParser.number({ value: g }));
rgbaFunc.append(valueParser.comma({ value: ',' }));
rgbaFunc.append(valueParser.number({ value: b }));
rgbaFunc.append(valueParser.comma({ value: ',' }));
rgbaFunc.append(valueParser.number({ value: a }));
rgbaFunc.append(valueParser.paren({ value: ')' }));
return rgbaFunc;
};