File: stylesheet.rb

package info (click to toggle)
ruby-roadie 5.2.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 528 kB
  • sloc: ruby: 3,418; makefile: 5
file content (65 lines) | stat: -rw-r--r-- 1,777 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# frozen_string_literal: true

module Roadie
  # Domain object that represents a stylesheet (from disc, perhaps).
  #
  # It has a name and a list of {StyleBlock}s.
  #
  # @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.
  # @attr_reader [Array<StyleBlock>] blocks
  class Stylesheet
    BOM = (+"\xEF\xBB\xBF").force_encoding("UTF-8").freeze

    attr_reader :name, :blocks

    # Parses the CSS string into a {StyleBlock}s and stores it.
    #
    # @param [String] name
    # @param [String] css
    def initialize(name, css)
      @name = name
      @blocks = parse_blocks(css.sub(BOM, ""))
    end

    def to_s
      blocks.join("\n")
    end

    private

    def inlinable_blocks
      blocks.select(&:inlinable?)
    end

    def parse_blocks(css)
      blocks = []
      parser = setup_parser(css)
      parser.each_rule_set do |rule_set, media_types|
        rule_set.selectors.each do |selector_string|
          blocks << create_style_block(selector_string, rule_set, media_types)
        end
      end

      blocks
    end

    def create_style_block(selector_string, rule_set, media_types)
      specificity = CssParser.calculate_specificity(selector_string)
      selector = Selector.new(selector_string, specificity)
      properties = []

      rule_set.each_declaration do |prop, val, important|
        properties << StyleProperty.new(prop, val, important, specificity)
      end

      StyleBlock.new(selector, properties, media_types)
    end

    def setup_parser(css)
      parser = CssParser::Parser.new
      # CssParser::Parser#add_block! mutates input parameter
      parser.add_block! css.dup
      parser
    end
  end
end