1
# frozen_string_literal: true
2

3 5
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 5
  class Stylesheet
11 5
    BOM = (+"\xEF\xBB\xBF").force_encoding('UTF-8').freeze
12

13 5
    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 5
    def initialize(name, css)
20 5
      @name = name
21 5
      @blocks = parse_blocks(css.sub(BOM, ""))
22
    end
23

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

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

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

42 5
      blocks
43
    end
44

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

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

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

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

Read our documentation on viewing source code .

Loading