Merge pull request from adroitwhiz/cast-to-black

Cast malformed color hex strings to RGBA 0,0,0,255 instead of null
This commit is contained in:
DD Liu 2020-09-03 15:52:52 -04:00 committed by GitHub
commit 7c652246df
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 7 additions and 2 deletions
src/util
test/unit

View file

@ -93,6 +93,9 @@ class Cast {
let color; let color;
if (typeof value === 'string' && value.substring(0, 1) === '#') { if (typeof value === 'string' && value.substring(0, 1) === '#') {
color = Color.hexToRgb(value); color = Color.hexToRgb(value);
// If the color wasn't *actually* a hex color, cast to black
if (!color) color = {r: 0, g: 0, b: 0, a: 255};
} else { } else {
color = Color.decimalToRgb(Cast.toNumber(value)); color = Color.decimalToRgb(Cast.toNumber(value));
} }

View file

@ -73,7 +73,7 @@ test('toString', t => {
t.end(); t.end();
}); });
test('toRbgColorList', t => { test('toRgbColorList', t => {
// Hex (minimal, see "color" util tests) // Hex (minimal, see "color" util tests)
t.deepEqual(cast.toRgbColorList('#000'), [0, 0, 0]); t.deepEqual(cast.toRgbColorList('#000'), [0, 0, 0]);
t.deepEqual(cast.toRgbColorList('#000000'), [0, 0, 0]); t.deepEqual(cast.toRgbColorList('#000000'), [0, 0, 0]);
@ -88,10 +88,11 @@ test('toRbgColorList', t => {
// Malformed // Malformed
t.deepEqual(cast.toRgbColorList('ffffff'), [0, 0, 0]); t.deepEqual(cast.toRgbColorList('ffffff'), [0, 0, 0]);
t.deepEqual(cast.toRgbColorList('foobar'), [0, 0, 0]); t.deepEqual(cast.toRgbColorList('foobar'), [0, 0, 0]);
t.deepEqual(cast.toRgbColorList('#nothex'), [0, 0, 0]);
t.end(); t.end();
}); });
test('toRbgColorObject', t => { test('toRgbColorObject', t => {
// Hex (minimal, see "color" util tests) // Hex (minimal, see "color" util tests)
t.deepEqual(cast.toRgbColorObject('#000'), {r: 0, g: 0, b: 0}); t.deepEqual(cast.toRgbColorObject('#000'), {r: 0, g: 0, b: 0});
t.deepEqual(cast.toRgbColorObject('#000000'), {r: 0, g: 0, b: 0}); t.deepEqual(cast.toRgbColorObject('#000000'), {r: 0, g: 0, b: 0});
@ -107,6 +108,7 @@ test('toRbgColorObject', t => {
// Malformed // Malformed
t.deepEqual(cast.toRgbColorObject('ffffff'), {a: 255, r: 0, g: 0, b: 0}); t.deepEqual(cast.toRgbColorObject('ffffff'), {a: 255, r: 0, g: 0, b: 0});
t.deepEqual(cast.toRgbColorObject('foobar'), {a: 255, r: 0, g: 0, b: 0}); t.deepEqual(cast.toRgbColorObject('foobar'), {a: 255, r: 0, g: 0, b: 0});
t.deepEqual(cast.toRgbColorObject('#nothex'), {a: 255, r: 0, g: 0, b: 0});
t.end(); t.end();
}); });