Skip to content

Commit

Permalink
directly substitute the hex in the replace callback (fixes last comme…
Browse files Browse the repository at this point in the history
  • Loading branch information
schelmo committed Apr 30, 2018
1 parent 76a4586 commit 871487c
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 19 deletions.
27 changes: 8 additions & 19 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,33 +33,22 @@ module.exports = postcss.plugin('postcss-hexrgba', () => {
* @param {string} decl CSS delcaration
*/
function ruleHandler(decl, result) {
let input = decl.value,
output = input,
hexes = [];
let input = decl.value;

// Get the raw hex values out of the decl value and put them in an array
input.replace(/rgba\(#(.*?),/g, (a, b) => hexes.push(b));

// If there are no hexes in the value, exit
if (!hexes.length) {
return;
}

// Convert each hex to RGB
hexes.forEach(hex => {
// Get the raw hex values and replace them
let output = input.replace(/rgba\(#(.*?),/g, (match, hex) => {
let rgb = hexRgb(hex),
matchHex = new RegExp('#' + hex);

// If conversion fails, warn and exit
// If conversion fails, emit a warning
if (!rgb) {
result.warn('not a valid hex', { node: decl });
return;
return match;
}

rgb = rgb.toString();

// Replace hex values in output string
output = output.replace(matchHex, rgb);

return match.replace(matchHex, rgb);
});

decl.replaceWith({
Expand Down
2 changes: 2 additions & 0 deletions test/fixtures/complex.css
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
.foo {
background: linear-gradient(rgba(#0fab53,.1), rgba(#000, 0.2));
background-image: linear-gradient(#f00, rgba(#f00, 0.2)),
linear-gradient(#0f0, rgba(#0f0, 0.2));
}
2 changes: 2 additions & 0 deletions test/fixtures/complex.expected.css
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
.foo {
background: linear-gradient(rgba(15,171,83,.1), rgba(0,0,0, 0.2));
background-image: linear-gradient(#f00, rgba(255,0,0, 0.2)),
linear-gradient(#0f0, rgba(0,255,0, 0.2));
}

0 comments on commit 871487c

Please sign in to comment.