Skip to content

Commit

Permalink
Fix shorthand alpha channel parsing. (#34)
Browse files Browse the repository at this point in the history
  • Loading branch information
ben-eb authored and Qix- committed Mar 9, 2017
1 parent efa8ffd commit eb857c2
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 3 deletions.
6 changes: 3 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ cs.get.rgb = function (string) {
return null;
}

var abbr = /^#([a-f0-9]{3,4})$/i;
var abbr = /^#([a-f0-9]{3})([a-f0-9]{1})?$/i;
var hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i;
var rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/;
var per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/;
Expand All @@ -58,15 +58,15 @@ cs.get.rgb = function (string) {
var hexAlpha;

if (match = string.match(abbr)) {
hexAlpha = match[2];
match = match[1];
hexAlpha = match[3];

for (i = 0; i < 3; i++) {
rgb[i] = parseInt(match[i] + match[i], 16);
}

if (hexAlpha) {
rgb[3] = Math.round(parseInt(hexAlpha + hexAlpha, 16) / 255);
rgb[3] = Math.round((parseInt(hexAlpha + hexAlpha, 16) / 255) * 100) / 100;
}
} else if (match = string.match(hex)) {
hexAlpha = match[2];
Expand Down
1 change: 1 addition & 0 deletions test/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ assert.deepEqual(string.get.rgb('blue'), [0, 0, 255, 1]);
assert.deepEqual(string.get.rgb('blue'), [0, 0, 255, 1]);

// alpha
assert.deepEqual(string.get.rgb('#fffa'), [255, 255, 255, 0.67]);
assert.deepEqual(string.get.rgb('#c814e933'), [200, 20, 233, 0.2]);
assert.deepEqual(string.get.rgb('#c814e900'), [200, 20, 233, 0]);
assert.deepEqual(string.get.rgb('#c814e9ff'), [200, 20, 233, 1]);
Expand Down

0 comments on commit eb857c2

Please sign in to comment.