Mange / roadie
1
# frozen_string_literal: true
2

3 6
module Roadie
4
  # Domain object that represents a stylesheet (from disc, perhaps).
5
  #
6
  # It has a name and a list of {StyleBlock}s.
7
  #
8
  # @attr_reader [String] name the name of the stylesheet ("stylesheets/main.css", "Admin user styles", etc.). The name of the stylesheet will be visible if any errors occur.
9
  # @attr_reader [Array<StyleBlock>] blocks
10 6
  class Stylesheet
11 6
    BOM = (+"\xEF\xBB\xBF").force_encoding('UTF-8').freeze
12

13 6
    attr_reader :name, :blocks
14

15
    # Parses the CSS string into a {StyleBlock}s and stores it.
16
    #
17
    # @param [String] name
18
    # @param [String] css
19 6
    def initialize(name, css)
20 6
      @name = name
21 6
      @blocks = parse_blocks(css.sub(BOM, ""))
22
    end
23

24 6
    def to_s
25 6
      blocks.join("\n")
26
    end
27

28 6
    private
29 6
    def inlinable_blocks
30 0
      blocks.select(&:inlinable?)
31
    end
32

33 6
    def parse_blocks(css)
34 6
      blocks = []
35 6
      parser = setup_parser(css)
36 6
      parser.each_rule_set do |rule_set, media_types|
37 6
        rule_set.selectors.each do |selector_string|
38 6
          blocks << create_style_block(selector_string, rule_set, media_types)
39
        end
40
      end
41

42 6
      blocks
43
    end
44

45 6
    def create_style_block(selector_string, rule_set, media_types)
46 6
      specificity = CssParser.calculate_specificity(selector_string)
47 6
      selector = Selector.new(selector_string, specificity)
48 6
      properties = []
49

50 6
      rule_set.each_declaration do |prop, val, important|
51 6
        properties << StyleProperty.new(prop, val, important, specificity)
52
      end
53

54 6
      StyleBlock.new(selector, properties, media_types)
55
    end
56

57 6
    def setup_parser(css)
58 6
      parser = CssParser::Parser.new
59
      # CssParser::Parser#add_block! mutates input parameter
60 6
      parser.add_block! css.dup
61 6
      parser
62
    end
63
  end
64
end

Read our documentation on viewing source code .

Loading