Class: Wunderbar::XmlMarkup

Inherits:
BuilderClass show all
Defined in:
lib/wunderbar/react.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.



130
131
132
133
134
135
136
137
138
139
# File 'lib/wunderbar/builder.rb', line 130

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



144
145
146
147
148
149
150
151
152
# File 'lib/wunderbar/builder.rb', line 144

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.



141
142
143
# File 'lib/wunderbar/builder.rb', line 141

def _width
  @_width
end

Class Method Details

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

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



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/wunderbar/builder.rb', line 111

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



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

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



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
378
379
380
381
382
383
384
385
386
387
# File 'lib/wunderbar/builder.rb', line 331

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



190
191
192
193
# File 'lib/wunderbar/builder.rb', line 190

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

#comment!(text) ⇒ Object



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

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

#compact!(&block) ⇒ Object



195
196
197
198
199
200
201
202
# File 'lib/wunderbar/builder.rb', line 195

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

#declare!(*args) ⇒ Object



170
171
172
# File 'lib/wunderbar/builder.rb', line 170

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

#indented_text!(text) ⇒ Object



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

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
end

#methodsObject



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

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

#pdf=(value) ⇒ Object



275
276
277
# File 'lib/wunderbar/builder.rb', line 275

def pdf=(value)
  @_pdf = value
end

#pdf?Boolean

Returns:

  • (Boolean)


279
280
281
# File 'lib/wunderbar/builder.rb', line 279

def pdf?
  @_pdf
end

#render(container, &block) ⇒ Object



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

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['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
  common = Ruby2JS.convert(block, scope: @_scope, react: true)
  server = "React.renderToString(#{common})"
  client = "React.render(#{common}, #{element})"

  # 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.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({})
  begin
    setup = []
    Wunderbar::Asset.scripts.each do |script|
      next unless script.options[:react]
      setup += script.options[:react] if Array === script.options[:react]

      if script.contents
        scripts.unshift script.contents
      elsif script.path
        scripts.unshift File.read(
          File.expand_path(script.path, Wunderbar::Asset.root))
      end
    end

    # concatenate and execute scripts on server
    scripts.unshift *setup.uniq
    context = ExecJS.compile(scripts.compact.join(";\n"))

    # insert results into target
    nodes = builder._ { context.eval(server) }
    nodes.each {|node| node.parent = target}
    target.children += nodes
  rescue ExecJS::ProgramError => e
    Wunderbar.error e
    target.children << builder._pre(e.message).node?
  end

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

#respond_to?(method) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#spaced!Object



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

def spaced!
  @spaced = true
end

#system(command, opts = {}) ⇒ Object

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



284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/wunderbar/builder.rb', line 284

def system(command, opts={})
  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 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



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

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



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

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

#text!(text) ⇒ Object



166
167
168
# File 'lib/wunderbar/builder.rb', line 166

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