Skip to content

Commit

Permalink
Fix hexadecimal transparent colors.
Browse files Browse the repository at this point in the history
  • Loading branch information
mbostock committed Apr 20, 2020
1 parent df60378 commit f176ff1
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/color.js
Expand Up @@ -198,8 +198,8 @@ export default function color(format) {
format = (format + "").trim().toLowerCase();
return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) // #ff0000
: l === 3 ? new Rgb((m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1) // #f00
: l === 8 ? new Rgb(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000
: l === 4 ? new Rgb((m >> 12 & 0xf) | (m >> 8 & 0xf0), (m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), (((m & 0xf) << 4) | (m & 0xf)) / 0xff) // #f000
: l === 8 ? rgba(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000
: l === 4 ? rgba((m >> 12 & 0xf) | (m >> 8 & 0xf0), (m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), (((m & 0xf) << 4) | (m & 0xf)) / 0xff) // #f000
: null) // invalid hex
: (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
: (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
Expand Down
7 changes: 7 additions & 0 deletions test/color-test.js
Expand Up @@ -146,6 +146,13 @@ tape("color(format) does not allow made-up names", function(test) {
test.end();
});

tape("color(format) allows achromatic colors", function(test) {
test.rgbEqual(color.color("rgba(0,0,0,0)"), NaN, NaN, NaN, 0);
test.rgbEqual(color.color("#0000"), NaN, NaN, NaN, 0);
test.rgbEqual(color.color("#00000000"), NaN, NaN, NaN, 0);
test.end();
});

tape("color(format) does not allow whitespace before open paren or percent sign", function(test) {
test.equal(color.color("rgb (120,30,50)"), null);
test.equal(color.color("rgb (12%,30%,50%)"), null);
Expand Down

0 comments on commit f176ff1

Please sign in to comment.