From 034a0ae44871e2c98b4b20c43b32ddcc4e6f2273 Mon Sep 17 00:00:00 2001 From: Rafael Caricio Date: Sat, 6 Sep 2014 15:53:38 +0200 Subject: [PATCH] Parse hex colors --- gradient-parser.js | 21 +++++++++++++++++---- spec/gradient-parser.spec.js | 25 +++++++++++++++++++++---- 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/gradient-parser.js b/gradient-parser.js index 03e45a3..b0ea32a 100644 --- a/gradient-parser.js +++ b/gradient-parser.js @@ -32,7 +32,9 @@ module.exports = (function() { angleValue: /^([0-9]+)deg/, startCall: /^\(/, endCall: /^\)/, - comma: /^,/ + comma: /^,/, + hexColor: /^\#([0-9a-fA-F]+)/, + literalColor: /^([a-zA-Z]+)/ }; var input = '', @@ -172,12 +174,12 @@ module.exports = (function() { } function matchColor() { - return matchLiteralColor(); + return matchLiteralColor() || + matchHexColor(); } function matchLiteralColor() { - var literalColors = /^([a-zA-Z]+)/, - captures = scan(literalColors); + var captures = scan(tokens.literalColor); if (captures) { return { @@ -187,6 +189,17 @@ module.exports = (function() { } } + function matchHexColor() { + var captures = scan(tokens.hexColor); + + if (captures) { + return { + type: 'hex', + value: captures[1] + }; + } + } + function matchLength() { return matchMetric(tokens.pixelValue, 'px') || matchMetric(tokens.percentageValue, '%') || diff --git a/spec/gradient-parser.spec.js b/spec/gradient-parser.spec.js index f8b841a..aa9ea69 100644 --- a/spec/gradient-parser.spec.js +++ b/spec/gradient-parser.spec.js @@ -159,13 +159,30 @@ describe('gradient-parser.js', function () { describe('parse orientation ' + orientation.type, function() { beforeEach(function() { ast = gradientParser('linear-gradient(' + orientation.unparsedValue + ', blue, green)'); - subject = ast[0]; + subject = ast[0].orientation; }); - it('should parse the ' + orientation.type + ' orientation', function() { - expect(subject.orientation.type).to.equal(orientation.type); - expect(subject.orientation.value).to.equal(orientation.value); + it('should parse value', function() { + expect(subject.type).to.equal(orientation.type); + expect(subject.value).to.equal(orientation.value); }); }); }); + + [ + {type: 'literal', unparsedValue: 'red', value: 'red'}, + {type: 'hex', unparsedValue: '#c2c2c2', value: 'c2c2c2'} + ].forEach(function(color) { + describe('parse color type '+ color.type, function() { + beforeEach(function() { + ast = gradientParser('linear-gradient(12deg, ' + color.unparsedValue + ', blue, green)'); + subject = ast[0].colorStops[0]; + }); + + it('should parse value', function() { + expect(subject.type).to.equal(color.type); + expect(subject.value).to.equal(color.value); + }); + }); + }); });