File tree Expand file tree Collapse file tree 3 files changed +82
-0
lines changed
Expand file tree Collapse file tree 3 files changed +82
-0
lines changed Original file line number Diff line number Diff line change 1414
1515require "csscss/parser/common"
1616require "csscss/parser/color"
17+ require "csscss/parser/background"
Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments