Skip to content

Commit 8406a2c

Browse files
committed
Implements the beginning of the background parser/transformer
Still needs some work
1 parent ff1bf36 commit 8406a2c

File tree

3 files changed

+82
-0
lines changed

3 files changed

+82
-0
lines changed

lib/csscss.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,4 @@
1414

1515
require "csscss/parser/common"
1616
require "csscss/parser/color"
17+
require "csscss/parser/background"

lib/csscss/parser/background.rb

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
module Csscss
2+
module Parser
3+
module Background
4+
class Parser < Parslet::Parser
5+
include Color
6+
7+
#rule(:background_color) { (color | symbol("inherit")).as(:bg_color) }
8+
#rule(:background_url) { (url | symbol("none") | symbol("inherit")).as(:bg_url) }
9+
10+
rule(:background_color) { color | symbol("inherit") }
11+
rule(:background_image) { url | (symbol("none") | symbol("inherit")).as(:image_literal) }
12+
13+
rule(:background) {
14+
(background_color.maybe.as(:bg_color) >> background_image.maybe.as(:bg_image)).as(:background)
15+
}
16+
root(:background)
17+
end
18+
19+
class Transformer < Parslet::Transform
20+
rule(rgb:{
21+
red:{percent:simple(:red)},
22+
green:{percent:simple(:green)},
23+
blue:{percent:simple(:blue)}
24+
}) { {rgb:{red:"#{red}%", green:"#{green}%", blue:"#{blue}%"}}}
25+
26+
rule(color:{rgb:subtree(:rgb)}) {
27+
"background-color: rgb(#{rgb[:red]}, #{rgb[:green]}, #{rgb[:blue]})"
28+
}
29+
30+
rule(color:{keyword:simple(:keyword)}) {
31+
"background-color: #{keyword.to_s.downcase}".strip
32+
}
33+
34+
rule(color:{hexcolor:simple(:value)}) {
35+
"background-color: ##{value}"
36+
}
37+
38+
rule(image_literal:simple(:url)) {"background-image: #{url}"}
39+
rule(url:simple(:url)) {"background-image: #{url}"}
40+
41+
rule(background: {
42+
bg_color:simple(:color),
43+
bg_image: simple(:url)
44+
}) {
45+
[color, url].compact
46+
}
47+
end
48+
end
49+
end
50+
end
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
require "test_helper"
2+
3+
module Csscss::Parser
4+
module Background
5+
describe Background do
6+
before do
7+
@parser = Parser.new
8+
@trans = Transformer.new
9+
end
10+
11+
def trans(s)
12+
@trans.apply(@parser.parse(s))
13+
end
14+
15+
it "converts color to shorthand" do
16+
trans("#fff").must_equal(["background-color: #fff"])
17+
trans("BLACK").must_equal(["background-color: black"])
18+
trans("inherit").must_equal(["background-color: inherit"])
19+
trans("inherit none").must_equal([
20+
"background-color: inherit",
21+
"background-image: none"
22+
])
23+
24+
trans("#fff url(http://foo.com/bar.jpg)").must_equal([
25+
"background-color: #fff",
26+
"background-image: url(http://foo.com/bar.jpg)"
27+
])
28+
end
29+
end
30+
end
31+
end

0 commit comments

Comments
 (0)