From fd1a517e84fb17d96b30536cded823651a32caf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrg=20Lehni?= Date: Sat, 6 Oct 2018 21:57:30 +0200 Subject: [PATCH] Improve hex Color parser Addresses changes in #1469 --- src/style/Color.js | 27 ++++++++++++++------------- test/tests/Color.js | 3 +++ 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/src/style/Color.js b/src/style/Color.js index bd7f602b..7395056f 100644 --- a/src/style/Color.js +++ b/src/style/Color.js @@ -59,21 +59,22 @@ var Color = Base.extend(new function() { colorCtx; function fromCSS(string) { - var match = string.match(/^#(\w{1,2})(\w{1,2})(\w{1,2})$/), + var match = string.match( + /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})([\da-f]{2})?$/i + ) || string.match( + /^#([\da-f])([\da-f])([\da-f])$/i + ), type = 'rgb', components; - if (/^#[A-Fa-f0-9]+$/.test( string )) { - // HEX / HEX+A - var base = string.replace(/^#/,''); - var size = base.length; - components = base.split( size <= 4 ? /(.)/ : /(..)/ ); - components = components.filter(Boolean).map(function(x) { - return parseInt(size <= 4 ? x + x : x, 16) / 255; - }); - - if ( !components[0] ) components[0] = 0; - if ( !components[1] ) components[1] = 0; - if ( !components[2] ) components[2] = 0; + if (match) { + // Hex with optional alpha channel: + var amount = match[4] ? 4 : 3; + components = new Array(amount); + for (var i = 0; i < amount; i++) { + var value = match[i + 1]; + components[i] = parseInt(value.length == 1 + ? value + value : value, 16) / 255; + } } else if (match = string.match(/^(rgb|hsl)a?\((.*)\)$/)) { // RGB / RGBA or HSL / HSLA type = match[1]; diff --git a/test/tests/Color.js b/test/tests/Color.js index f8afec52..16eabba5 100644 --- a/test/tests/Color.js +++ b/test/tests/Color.js @@ -66,6 +66,9 @@ test('Creating Colors', function() { equals(new Color('#ff0000'), new Color(1, 0, 0), 'Color from hex string'); + equals(new Color('#FF3300'), new Color(1, 0.2, 0), + 'Color from hex string'); + equals(new Color('#ff000099'), new Color(1, 0, 0, .6), 'Color from hex code with alpha');