Skip to content

Commit f8bf28c

Browse files
committed
Implements color parser
1 parent def804d commit f8bf28c

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed

lib/csscss.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,4 @@
1313
require "csscss/json_reporter"
1414

1515
require "csscss/parser/common"
16+
require "csscss/parser/color"

lib/csscss/parser/color.rb

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
module Csscss
2+
module Parser
3+
module Color
4+
include Parslet
5+
include Common
6+
7+
rule(:color) { hexcolor | rgb | color_keyword }
8+
rule(:rgb) { rgb_with(numbers) | rgb_with(percent) }
9+
rule(:hexcolor) { str("#") >> match["a-fA-F0-9"].repeat(1) >> spaces }
10+
rule(:color_keyword) {
11+
colors = %w(inherit black silver gray white maroon
12+
red purple fuchsia green lime olive
13+
yellow navy blue teal aqua)
14+
colors.map {|c| symbol(c) }.reduce(:|)
15+
}
16+
17+
private
18+
def rgb_with(parser)
19+
symbol("rgb") >> parens do
20+
parser >> spaces >>
21+
symbol(",") >>
22+
parser >> spaces >>
23+
symbol(",") >>
24+
parser >> spaces
25+
end
26+
end
27+
end
28+
end
29+
end

test/csscss/parser/color_test.rb

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
require "test_helper"
2+
3+
module Csscss::Parser
4+
describe Color do
5+
class ColorTest
6+
include Color
7+
end
8+
9+
before { @parser = ColorTest.new }
10+
11+
describe "color" do
12+
it "parses color" do
13+
@parser.color.must_parse "rgb(123, 222, 444)"
14+
@parser.color.must_parse "rgb(123%, 222%, 444%)"
15+
@parser.color.must_parse "#ffffff"
16+
@parser.color.must_parse "inherit"
17+
@parser.color.must_parse "black"
18+
end
19+
end
20+
21+
describe "individual rules" do
22+
it "parses rgb number color" do
23+
@parser.rgb.must_parse "rgb(123, 222, 444)"
24+
@parser.rgb.must_parse "rgb ( 123 , 222 , 444 ) "
25+
@parser.rgb.must_not_parse "rgb(1aa, 222, 444)"
26+
end
27+
28+
it "parses rgb percentage color" do
29+
@parser.rgb.must_parse "rgb(123%, 222%, 444%)"
30+
@parser.rgb.must_parse "rgb ( 123% , 222% , 444% ) "
31+
@parser.rgb.must_not_parse "rgb(1aa%, 222%, 444%)"
32+
end
33+
34+
it "parses hex colors" do
35+
@parser.hexcolor.must_parse "#ffffff"
36+
@parser.hexcolor.must_parse "#ffffff "
37+
@parser.hexcolor.must_parse "#fff "
38+
@parser.hexcolor.must_parse "#fFF123"
39+
@parser.hexcolor.must_not_parse "fFF123"
40+
end
41+
42+
it "parses keyword colors" do
43+
@parser.color_keyword.must_parse "inherit"
44+
@parser.color_keyword.must_parse "inherit "
45+
46+
@parser.color_keyword.must_parse "black"
47+
@parser.color_keyword.must_parse "BLACK"
48+
end
49+
end
50+
end
51+
end

0 commit comments

Comments
 (0)