Class: Sass::Tree::Visitors::ToCss

Inherits:
Base
  • Object
show all
Defined in:
/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb

Overview

A visitor for converting a Sass tree into CSS.

Constant Summary

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Methods inherited from Base

node_name, visit, #visit_children, #visit_if

Constructor Details

- (ToCss) initialize(build_source_mapping = false)

Returns a new instance of ToCss

Parameters:

  • build_source_mapping (Boolean) (defaults to: false)

    Whether to build a Source::Map while creating the CSS output. The mapping will be available from #source_mapping after the visitor has completed.



11
12
13
14
15
16
17
18
19
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 11

def initialize(build_source_mapping = false)
  @tabs = 0
  @line = 1
  @offset = 1
  @result = ""
  @source_mapping = build_source_mapping ? Sass::Source::Map.new : nil
  @lstrip = nil
  @in_directive = false
end

Instance Attribute Details

- source_mapping (readonly)

The source mapping for the generated CSS file. This is only set if build_source_mapping is passed to the constructor and Engine#render has been run.



6
7
8
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 6

def source_mapping
  @source_mapping
end

Instance Method Details

- erase!(chars) (protected)

Move the output cursor back chars characters.



61
62
63
64
65
66
67
68
69
70
71
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 61

def erase!(chars)
  return if chars == 0
  str = @result.slice!(-chars..-1)
  newlines = str.count("\n")
  if newlines > 0
    @line -= newlines
    @offset = @result[@result.rindex("\n") || 0..-1].size
  else
    @offset -= chars
  end
end

- for_node(node, attr_prefix = nil) (protected)

Associate all output produced in a block with a given node. Used for source mapping.



43
44
45
46
47
48
49
50
51
52
53
54
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 43

def for_node(node, attr_prefix = nil)
  return yield unless @source_mapping
  start_pos = Sass::Source::Position.new(@line, @offset)
  yield

  range_attr = attr_prefix ? :"#{attr_prefix}_source_range" : :source_range
  return if node.invisible? || !node.send(range_attr)
  source_range = node.send(range_attr)
  target_end_pos = Sass::Source::Position.new(@line, @offset)
  target_range = Sass::Source::Range.new(start_pos, target_end_pos, nil)
  @source_mapping.add(source_range, target_range)
end

- lstrip (protected)

lstrip the first output in the given block.



102
103
104
105
106
107
108
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 102

def lstrip
  old_lstrip = @lstrip
  @lstrip = true
  yield
ensure
  @lstrip &&= old_lstrip
end

- output(s) (protected)

Add s to the output string and update the line and offset information accordingly.



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 79

def output(s)
  if @lstrip
    s = s.gsub(/\A\s+/, "")
    @lstrip = false
  end

  newlines = s.count(NEWLINE)
  if newlines > 0
    @line += newlines
    @offset = s[s.rindex(NEWLINE)..-1].size
  else
    @offset += s.size
  end

  @result << s
end

- prepend!(prefix) (protected)

Prepend prefix to the output string.



111
112
113
114
115
116
117
118
119
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 111

def prepend!(prefix)
  @result.insert 0, prefix
  return unless @source_mapping

  line_delta = prefix.count("\n")
  offset_delta = prefix.gsub(/.*\n/, '').size
  @source_mapping.shift_output_offsets(offset_delta)
  @source_mapping.shift_output_lines(line_delta)
end

- rstrip! (protected)

Strip all trailing whitespace from the output string.



97
98
99
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 97

def rstrip!
  erase! @result.length - 1 - (@result.rindex(/[^\s]/) || -1)
end

- (Boolean) trailing_semicolon? (protected)

Returns:

  • (Boolean)


56
57
58
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 56

def trailing_semicolon?
 @result.end_with?(";") && !@result.end_with?('\;')
end

- (String) visit(node)

Runs the visitor on node.

Parameters:

Returns:

  • (String)

    The CSS output.



25
26
27
28
29
30
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 25

def visit(node)
  super
rescue Sass::SyntaxError => e
  e.modify_backtrace(:filename => node.filename, :line => node.line)
  raise e
end

- visit_charset(node) (protected)



155
156
157
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 155

def visit_charset(node)
  for_node(node) {output("@charset \"#{node.name}\";")}
end

- visit_comment(node) (protected)



159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 159

def visit_comment(node)
  return if node.invisible?
  spaces = ('  ' * [@tabs - node.resolved_value[/^ */].size, 0].max)
  output(spaces)

  content = node.resolved_value.split("\n").join("\n" + spaces)
  if node.type == :silent
    content.gsub!(%r{^(\s*)//(.*)$}) {"#{$1}/*#{$2} */"}
  end
  if (node.style == :compact || node.style == :compressed) && node.type != :loud
    content.gsub!(%r{\n +(\* *(?!/))?}, ' ')
  end
  for_node(node) {output(content)}
end

- visit_cssimport(node) (protected)



259
260
261
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 259

def visit_cssimport(node)
  visit_directive(node)
end

- visit_directive(node) (protected)



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 176

def visit_directive(node)
  was_in_directive = @in_directive
  tab_str = '  ' * @tabs
  if !node.has_children || node.children.empty?
    output(tab_str)
    for_node(node) {output(node.resolved_value)}
    if node.has_children
      output("#{' ' unless node.style == :compressed}{}")
    elsif node.children.empty?
      output(";")
    end
    return
  end

  @in_directive ||= !node.is_a?(Sass::Tree::MediaNode)
  output(tab_str) if node.style != :compressed
  for_node(node) {output(node.resolved_value)}
  output(node.style == :compressed ? "{" : " {")
  output(node.style == :compact ? ' ' : "\n") if node.style != :compressed

  had_children = true
  first = true
  node.children.each do |child|
    next if child.invisible?
    if node.style == :compact
      if child.is_a?(Sass::Tree::PropNode)
        with_tabs(first || !had_children ? 0 : @tabs + 1) do
          visit(child)
          output(' ')
        end
      else
        unless had_children
          erase! 1
          output "\n"
        end

        if first
          lstrip {with_tabs(@tabs + 1) {visit(child)}}
        else
          with_tabs(@tabs + 1) {visit(child)}
        end

        rstrip!
        output "\n"
      end
      had_children = child.has_children
      first = false
    elsif node.style == :compressed
      unless had_children
        output(";") unless trailing_semicolon?
      end
      with_tabs(0) {visit(child)}
      had_children = child.has_children
    else
      with_tabs(@tabs + 1) {visit(child)}
      output "\n"
    end
  end
  rstrip!
  if node.style == :compressed && trailing_semicolon?
    erase! 1
  end
  if node.style == :expanded
    output("\n#{tab_str}")
  elsif node.style != :compressed
    output(" ")
  end
  output("}")
ensure
  @in_directive = was_in_directive
end

- visit_keyframerule(node) (protected)



381
382
383
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 381

def visit_keyframerule(node)
  visit_directive(node)
end

- visit_media(node) (protected)



250
251
252
253
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 250

def visit_media(node)
  with_tabs(@tabs + node.tabs) {visit_directive(node)}
  output("\n") if node.style != :compressed && node.group_end
end

- visit_prop(node) (protected)



263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 263

def visit_prop(node)
  return if node.resolved_value.empty?
  tab_str = '  ' * (@tabs + node.tabs)
  output(tab_str)
  for_node(node, :name) {output(node.resolved_name)}
  if node.style == :compressed
    output(":")
    for_node(node, :value) {output(node.resolved_value)}
  else
    output(": ")
    for_node(node, :value) {output(node.resolved_value)}
    output(";")
  end
end

- visit_root(node) (protected)



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 121

def visit_root(node)
  node.children.each do |child|
    next if child.invisible?
    visit(child)
    next if node.style == :compressed
    output "\n"
    next unless child.is_a?(Sass::Tree::DirectiveNode) && child.has_children && !child.bubbles?
    output "\n"
  end
  rstrip!
  if node.style == :compressed && trailing_semicolon?
    erase! 1
  end
  return "" if @result.empty?

  output "\n"

  unless Sass::Util.ruby1_8? || @result.ascii_only?
    if node.style == :compressed
      # A byte order mark is sufficient to tell browsers that this
      # file is UTF-8 encoded, and will override any other detection
      # methods as per http://encoding.spec.whatwg.org/#decode-and-encode.
      prepend! "\uFEFF"
    else
      prepend! "@charset \"UTF-8\";\n"
    end
  end

  @result
rescue Sass::SyntaxError => e
  e.sass_template ||= node.template
  raise e
end

- visit_rule(node) (protected)



280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 280

def visit_rule(node)
  with_tabs(@tabs + node.tabs) do
    rule_separator = node.style == :compressed ? ',' : ', '
    line_separator =
      case node.style
      when :nested, :expanded; "\n"
      when :compressed; ""
      else; " "
      end
    rule_indent = '  ' * @tabs
    per_rule_indent, total_indent = if [:nested, :expanded].include?(node.style)
                                      [rule_indent, '']
                                    else
                                      ['', rule_indent]
                                    end

    joined_rules = node.resolved_rules.members.map do |seq|
      next if seq.has_placeholder?
      rule_part = seq.to_s(:style => node.style)
      if node.style == :compressed
        rule_part.gsub!(/([^,])\s*\n\s*/m, '\1 ')
        rule_part.gsub!(/\s*([+>])\s*/m, '\1')
        rule_part.gsub!(/nth([^( ]*)\(([^)]*)\)/m) do |match|
          match.tr(" \t\n", "")
        end
        rule_part.strip!
      end
      rule_part
    end.compact.join(rule_separator)

    joined_rules.lstrip!
    joined_rules.gsub!(/\s*\n\s*/, "#{line_separator}#{per_rule_indent}")

    old_spaces = '  ' * @tabs
    if node.style != :compressed
      if node.options[:debug_info] && !@in_directive
        visit(debug_info_rule(node.debug_info, node.options))
        output "\n"
      elsif node.options[:trace_selectors]
        output("#{old_spaces}/* ")
        output(node.stack_trace.gsub("\n", "\n   #{old_spaces}"))
        output(" */\n")
      elsif node.options[:line_comments]
        output("#{old_spaces}/* line #{node.line}")

        if node.filename
          relative_filename =
            if node.options[:css_filename]
              begin
                Sass::Util.relative_path_from(
                  node.filename, File.dirname(node.options[:css_filename])).to_s
              rescue ArgumentError
                nil
              end
            end
          relative_filename ||= node.filename
          output(", #{relative_filename}")
        end

        output(" */\n")
      end
    end

    end_props, trailer, tabs = '', '', 0
    if node.style == :compact
      separator, end_props, bracket = ' ', ' ', ' { '
      trailer = "\n" if node.group_end
    elsif node.style == :compressed
      separator, bracket = ';', '{'
    else
      tabs = @tabs + 1
      separator, bracket = "\n", " {\n"
      trailer = "\n" if node.group_end
      end_props = (node.style == :expanded ? "\n" + old_spaces : ' ')
    end
    output(total_indent + per_rule_indent)
    for_node(node, :selector) {output(joined_rules)}
    output(bracket)

    with_tabs(tabs) do
      node.children.each_with_index do |child, i|
        if i > 0
          if separator.start_with?(";") && trailing_semicolon?
            erase! 1
          end
          output(separator)
        end
        visit(child)
      end
    end
    if node.style == :compressed && trailing_semicolon?
      erase! 1
    end

    output(end_props)
    output("}" + trailer)
  end
end

- visit_supports(node) (protected)



255
256
257
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 255

def visit_supports(node)
  visit_media(node)
end

- with_tabs(tabs) (protected)



34
35
36
37
38
39
# File '/Users/ceppstei/Projects/sass-lang/.sass/lib/sass/tree/visitors/to_css.rb', line 34

def with_tabs(tabs)
  old_tabs, @tabs = @tabs, tabs
  yield
ensure
  @tabs = old_tabs
end