Class: Wunderbar::XmlMarkup

Inherits:
BuilderClass show all
Defined in:
lib/wunderbar/render.rb,
lib/wunderbar/builder.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BuilderClass

#websocket

Methods inherited from BuilderBase

#get_binding, #set_variables_from_params

Constructor Details

#initialize(args = {}) ⇒ XmlMarkup

Returns a new instance of XmlMarkup.



137
138
139
140
141
142
143
144
145
146
# File 'lib/wunderbar/builder.rb', line 137

def initialize(args={})
  @_scope = args.delete(:scope)
  @_indent = args.delete(:indent) || Wunderbar.option[:indent]
  @_width = args.delete(:width) || Wunderbar.option[:width]
  @_pdf = false
  @doc = Node.new(nil)
  @node = @doc
  @indentation_enabled = true
  @spaced = false
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object

forward to Wunderbar or @_scope



151
152
153
154
155
156
157
158
159
# File 'lib/wunderbar/builder.rb', line 151

def method_missing(method, *args, &block)
  if Wunderbar.respond_to? method
    Wunderbar.send method, *args, &block
  elsif @_scope and @_scope.respond_to? method
    @_scope.send method, *args, &block
  else
    super
  end
end

Instance Attribute Details

#_widthObject

Returns the value of attribute _width.



148
149
150
# File 'lib/wunderbar/builder.rb', line 148

def _width
  @_width
end

Class Method Details

.dump(content, args = {}) ⇒ Object

convenience method for taking an XML node or string and formatting it



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/wunderbar/builder.rb', line 118

def self.dump(content, args={})
  markup = self.new(args)

  if Nokogiri::XML::Document === content and content.root.name == 'html'
    markup.declare! :DOCTYPE, :html
  end

  unless Nokogiri::XML::Node === content
    if defined? Nokogiri::HTML5.fragment
      content = Nokogiri::HTML5.fragment(content.to_s)
    else
      content = Nokogiri::HTML.fragment(content.to_s)
    end
  end

  markup[content]
  markup.target!
end

Instance Method Details

#<<(data) ⇒ Object

insert verbatim



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
# File 'lib/wunderbar/builder.rb', line 315

def <<(data)
  if defined? Nokogiri
    if not String === data or data.include? '<' or data.include? '&'
      # https://github.com/google/gumbo-parser/issues/266
      data = Nokogiri::HTML::fragment(data.to_s).to_xml

      # fix CDATA in most cases (notably scripts)
      data.gsub!(/<!\[CDATA\[(.*?)\]\]>/m) do
        if $1.include? '<' or $1.include? '&'
          "//<![CDATA[\n#{$1}\n//]]>"
        else
          $1
        end
      end

      # fix CDATA for style elements
      data.gsub!(/<style([^>])*>\/\/<!\[CDATA\[\n(.*?)\s+\/\/\]\]>/m) do
        if $2.include? '<' or $2.include? '&'
          "<style#{$1}>/*<![CDATA[*/\n#{$2.gsub("\n\Z",'')}\n/*]]>*/"
        else
          $1
        end
      end
    end
  end

  if String === data
    @node.children << data
  else
    @node.add_child data
  end
end

#[](*children) ⇒ Object



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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
# File 'lib/wunderbar/builder.rb', line 348

def [](*children)
  if children.length == 1
    if children.first.respond_to? :root
      children = [children.first.root]
    elsif defined? Nokogiri::XML::DocumentFragment and
      Nokogiri::XML::DocumentFragment === children.first
    then
      children = children.first.children
    end
  end

  # remove leading and trailing space
  if children.first.text? and children.first.text.strip.empty?
    children.shift
  end

  if not children.empty?
    children.pop if children.last.text? and children.last.text.strip.empty?
  end

  children.map do |child|
    if child.text? or child.cdata?
      text = child.text
      if not @indentation_enabled
        text! text
      elsif text.strip.empty?
        text! "" if text.count("\n")>1
      else
        indented_text! text
      end
    elsif child.comment?
      comment! child.text.sub(/\A /,'').sub(/ \Z/, '')
    elsif HtmlMarkup.flatten? child.children
      # disable indentation on the entire element
      compact! { tag!(child) {self[*child.children]} }
    elsif child.children.empty? and HtmlMarkup::VOID.include? child.name
      tag!(child)
    elsif child.children.all?(&:text?) and child.text
      tag!(child, @indentation_enabled ? child.text.strip : child.text)
    elsif child.children.any?(&:cdata?) and child.text =~ /[<&]/
      self << child
    elsif child.name == 'pre'
      compact! { tag!(child) {self[*child.children]} }
    elsif child.name == 'head'
      head = tag!(child) {self[*child.children]}
      html = @doc.children.last
      if html.name == :html
        head.parent.children.pop
        html.children.unshift head
        head.parent = html
      end
      head
    elsif not Nokogiri::XML::DTD === child
      tag!(child) {self[*child.children]}
    end
  end
end

#clear!Object



204
205
206
207
# File 'lib/wunderbar/builder.rb', line 204

def clear!
  @doc.children.clear
  @node = @doc
end

#comment!(text) ⇒ Object



185
186
187
188
189
# File 'lib/wunderbar/builder.rb', line 185

def comment! text
  comment = CommentNode.new(text)
  @node.children << comment
  comment
end

#compact!(&block) ⇒ Object



209
210
211
212
213
214
215
216
# File 'lib/wunderbar/builder.rb', line 209

def compact!(&block)
  begin
    indentation_enabled, @indentation_enabled = @indentation_enabled, false
    block.call
  ensure
    @indentation_enabled = indentation_enabled
  end
end

#declare!(*args) ⇒ Object



179
180
181
182
183
# File 'lib/wunderbar/builder.rb', line 179

def declare! *args
  doctype = DocTypeNode.new(*args)
  @node.children << doctype
  doctype
end

#indented_text!(text) ⇒ Object



191
192
193
194
195
196
197
198
# File 'lib/wunderbar/builder.rb', line 191

def indented_text!(text)
  return if text.length == 0 and not @spaced
  text = IndentedTextNode.new(text)
  text.extend SpacedNode if @spaced
  @node.children << text
  @spaced = false
  text
end

#methodsObject



161
162
163
164
165
# File 'lib/wunderbar/builder.rb', line 161

def methods
  result = super + Wunderbar.methods
  result += @_scope.methods if @_scope
  result.uniq
end

#pdf=(value) ⇒ Object



289
290
291
# File 'lib/wunderbar/builder.rb', line 289

def pdf=(value)
  @_pdf = value
end

#pdf?Boolean

Returns:

  • (Boolean)


293
294
295
# File 'lib/wunderbar/builder.rb', line 293

def pdf?
  @_pdf
end

#render(container, &block) ⇒ Object



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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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
154
155
156
157
158
159
160
# File 'lib/wunderbar/render.rb', line 28

def render(container, &block)
  csspath = Wunderbar::Node.parse_css_selector(container)
  root = @node.root

  # find the scripts and target on the page
  scripts = root.search('script')
  target = root.at(container)

  # compute base
  base = root.at('base')
  base = base && base.attrs[:href]
  base ||= @_scope.env['REQUEST_URI'][/.*\//]

  _base = @_scope.env['HTTP_X_WUNDERBAR_BASE']
  base = base[_base.length..-1] if _base and base.start_with? _base

  if base == '..' or base.end_with? '/..'
    base = (Pathname.new(@_scope.env['REQUEST_URI']) + '../' + base).to_s
  end

  script = @_scope.env['SCRIPT_NAME']
  base = base[script.length..-1] if script and base.start_with? script

  base = base[1..-1] if base.start_with? '/'

  # compute client side container
  element = "document.querySelector(#{container.inspect})"
  if csspath.length == 1 and csspath[0].length == 1
    value = csspath[0].values.first
    case csspath[0].keys.first
    when :id
      element = "document.getElementById(#{value.inspect})"
    when :class
      value = value.join(' ')
      element = "document.getElementsByClassName(#{value.inspect})[0]"
    when :name
      element = "document.getElementsByTagName(#{value.inspect})[0]"
    end
  end

  # build client and server scripts
  options = Wunderbar::Render::RUBY2JS_OPTIONS.merge(scope: @_scope,
    strict: false)
  common = Ruby2JS.convert(block, options)
  server = Wunderbar::Render.server(common)
  client = Wunderbar::Render.client(common, element, target)

  # extract content of scripts
  scripts.map! do |script|
    result = nil
    next if Wunderbar::ClientScriptNode === script

    if script.attrs[:src]
      src = script.attrs[:src]

      src = File.join(base, src) if not base.empty?
      src = src.sub(/\?.*$/, '') # strip queries (typically mtimes)
      src.untaint

      name = File.expand_path(src, @_scope.settings.public_folder.untaint)
      name.untaint unless src.tainted?
      if File.exist? name
        result = File.read(name)
      else
        file = File.expand_path(src+'.rb', @_scope.settings.views.untaint)
        result = Wunderbar::Asset.convert(file)
      end
    else
      result = Ruby2JS.convert(script.block, binding: script.binding)
    end

    result
  end

  builder = Wunderbar::HtmlMarkup.new({})
  setup = []
  requires = {}
  browserify = false
  Wunderbar::Asset.scripts.each do |script|
    next unless script.options[:render]
    setup += script.options[:render] if Array === script.options[:render]
    requires.merge! script.options[:require] if script.options[:require]
    browserify = true if script.options[:browserify]

    if script.contents
      scripts.unshift script.contents
    elsif script.path
      if script.path.start_with? '/'
        path = (ENV['DOCUMENT_ROOT'] + script.path).untaint
      else
        path = File.expand_path(script.path, Wunderbar::Asset.root).untaint
      end
      setup << File.read(script.options[:server].untaint || path)
    end
  end

  # concatenate and execute scripts on server
  if browserify
    setup += requires.map {|key, value| 
      "const #{key}=module.exports.#{key} || require(#{value.inspect})"
    }
  end
  scripts.unshift *setup.uniq
  html = Wunderbar::Render.eval(scripts, server)

  # insert results into target
  nodes = Wunderbar::Render.extract(builder._ { html })

  begin
    if nodes.length == 1
      nodes.each {|node| node.parent = target}
      target.children += nodes
    else
      span = Wunderbar::Node.new('span')
      nodes.each {|node| node.parent = span}
      span.children += nodes
      target.children << span
    end
  rescue => e
    span = Wunderbar::Node.new('span',
      style: 'background-color:#ff0; margin: 1em 0; padding: 1em; ' +
             'border: 4px solid red; border-radius: 1em')
    span.children << Wunderbar::Node.new('pre', e.to_s)
    span.children << Wunderbar::Node.new('pre', e.backtrace.join("\n"))
    span.children << Wunderbar::Node.new('pre', html)
    span.children << Wunderbar::Node.new('pre', nodes.inspect)
    span.children.each {|node| node.parent = span}
    target.children << span
  end

  # add client side script
  tag! 'script', Wunderbar::ClientScriptNode, client
end

#respond_to?(method) ⇒ Boolean

Returns:

  • (Boolean)


167
168
169
170
171
# File 'lib/wunderbar/builder.rb', line 167

def respond_to?(method)
  respond true if Wunderbar.respond_to? method
  respond true if @_scope and @_scope.respond_to? method
  super
end

#spaced!Object



218
219
220
# File 'lib/wunderbar/builder.rb', line 218

def spaced!
  @spaced = true
end

#system(*args) ⇒ Object

execute a system command, echoing stdin, stdout, and stderr



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/wunderbar/builder.rb', line 298

def system(*args)
  opts = {}
  opts = args.pop if Hash === args.last

  tag  = opts[:tag]  || 'pre'
  output_class = opts[:class] || {}
  output_class[:stdin]  ||= '_stdin'
  output_class[:stdout] ||= '_stdout'
  output_class[:stderr] ||= '_stderr'
  output_class[:hilite] ||= '_stdout _hilite'

  super(*args, opts) do |kind, line|
    tag! tag, line, class: output_class[kind]
  end
end

#tag!(sym, *args, &block) ⇒ Object

avoid method_missing overhead for the most common case



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/wunderbar/builder.rb', line 223

def tag!(sym, *args, &block)
  current_node = @node

  if sym.respond_to? :children
    node = sym
    attributes = node.attributes
    if node.attribute_nodes.any?(&:namespace)
      attributes = Hash[node.attribute_nodes.map { |attr| 
        name = attr.name
        name = "#{attr.namespace.prefix}:#{name}" if attr.namespace
        [name, attr.value]
      }]
    end

    attributes.merge!(node.namespaces) if node.namespaces
    args.push attributes
    if node.namespace and node.namespace.prefix
      sym = "#{node.namespace.prefix}:#{node.name}"
    else
      sym = node.name
    end

    unless Class === args.first
      args.unshift PreformattedNode if sym == 'pre'
      args.unshift ScriptNode if sym == 'script'
      args.unshift StyleNode if sym == 'style'
    end
  end

  children = nil
  if block and block.arity !=0
    if args.first and args.first.respond_to? :each
      children = args.shift
    end
  end

  if Class === args.first and args.first < Node
    node = args.shift.new sym, *args
  else
    node = Node.new sym, *args
  end

  node.extend CompactNode unless @indentation_enabled

  if @spaced
    node.extend SpacedNode
    @spaced = false
  end

  node.text = args.shift if String === args.first
  @node.add_child node
  @node = node
  if block
    if children
      children.each {|child| block.call(child)}
    else
      block.call(self)
    end
    @node.children << nil if @node.children.empty?
  end

  node
ensure
  @node = current_node
end

#target!Object



200
201
202
# File 'lib/wunderbar/builder.rb', line 200

def target!
  "#{@doc.serialize(indent: ' ' * @_indent, width: @_width).join("\n")}\n"
end

#text!(text) ⇒ Object



173
174
175
176
177
# File 'lib/wunderbar/builder.rb', line 173

def text! text
  text = TextNode.new(text)
  @node.children << text
  text
end