Class: Template

Inherits:
Object show all
Defined in:
lib/volt/server/template_parser.rb

Overview

TODO: The section_name that we’re passing in should probably be abstracted out. Possibly this whole thing needs a rewrite.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(template_parser, section_name, template, scope = Scope.new) ⇒ Template

Returns a new instance of Template.



11
12
13
14
15
16
17
18
19
# File 'lib/volt/server/template_parser.rb', line 11

def initialize(template_parser, section_name, template, scope=Scope.new)
   @binding_number = 0

	@template_parser = template_parser
   @section_name = section_name
	@template = template
   @scopes = [scope]
   @current_scope = @scopes.first
end

Instance Attribute Details

#current_scopeObject

Returns the value of attribute current_scope.



9
10
11
# File 'lib/volt/server/template_parser.rb', line 9

def current_scope
  @current_scope
end

#section_nameObject

Returns the value of attribute section_name.



9
10
11
# File 'lib/volt/server/template_parser.rb', line 9

def section_name
  @section_name
end

Instance Method Details

#add_attribute_binding(node, attribute, content) ⇒ Object

Attribute bindings support multiple handlebar listeners Exvoltle:

<button click="{_primary} {_important}">...

To accomplish this, we create a new listener from the existing ones in the Proc that we pass to the binding when it is created.



175
176
177
178
179
180
181
182
183
184
185
# File 'lib/volt/server/template_parser.rb', line 175

def add_attribute_binding(node, attribute, content)
	setup_node_id(node)
   
   if content =~ /^\{[^\{]+\}$/
     # Getter is the content inside of { ... }
     add_single_getter(node, attribute, content)
   else
     add_multiple_getters(node, attribute, content)
   end

end

#add_binding(node, content) ⇒ Object



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
# File 'lib/volt/server/template_parser.rb', line 39

def add_binding(node, content)
	if content[0] == '/'
		add_close_mustache(node)
	elsif content[0] == '#'
		command, *content = content.split(/ /)
		content = content.join(' ')

		case command
	  when '#template'
	    return add_template(node, content)
		when '#each'
			return add_each_binding(node, content)
		when '#if'
			return add_if_binding(node, content)
     when '#elsif'
       return add_else_binding(node, content)
     when '#else'
       if content.present?
         # TODO: improve error, include line/file
         raise "#else should not include a condition, use #elsif instead.  #{content} was passed as a condition."
       end
       
       return add_else_binding(node, nil)
		else
			# TODO: Handle invalid command
			raise "Invalid Command"
		end
	else
		# text binding
		return add_text_binding(content)
	end
end

#add_close_mustache(node, close_if = true) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/volt/server/template_parser.rb', line 134

def add_close_mustache(node, close_if=true)
	scope = @scopes.pop
	@current_scope = @scopes.last
   
   # Close an outstanding if binding (if it exists)
   @current_scope.close_if_binding! if close_if
   
	# Track that this scope was closed out
	@current_scope.add_closed_child_scope(scope)

	html = "<!-- $/#{scope.outer_binding_number} -->"

	return html
end

#add_each_binding(node, content) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/volt/server/template_parser.rb', line 81

def add_each_binding(node, content)
	html = "<!-- $#{@binding_number} -->"
   
   content, variable_name = content.strip.split(/ as /)

   template_name = "#{@template_parser.template_path}/#{section_name}/__template/#{@binding_number}"
	@current_scope.add_binding(@binding_number, "lambda { |target, context, id| EachBinding.new(target, context, id, Proc.new { #{content} }, #{variable_name.inspect}, #{template_name.inspect}) }")

	# Add the node, the binding number, then store the location where the
	# bindings for this block starts.
	@current_scope = Scope.new(@binding_number)
	@scopes << @current_scope

	@binding_number += 1
	return html
end

#add_else_binding(node, content) ⇒ Object



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/volt/server/template_parser.rb', line 116

def add_else_binding(node, content)
  html = add_close_mustache(node, false)
  
html += "<!-- $#{@binding_number} -->"
  template_name = "#{@template_parser.template_path}/#{section_name}/__template/#{@binding_number}"
  
  @current_scope.current_if_binding[1].add_branch(content, template_name)
  
# Add the node, the binding number, then store the location where the
# bindings for this block starts.
@current_scope = Scope.new(@binding_number)
@scopes << @current_scope

@binding_number += 1
  
  return html
end

#add_event_binding(node, attribute_name, content) ⇒ Object



230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/volt/server/template_parser.rb', line 230

def add_event_binding(node, attribute_name, content)
  setup_node_id(node)
  
  event = attribute_name[2..-1]
  
  if node.name == 'a'
    # For links, we need to add blank href to make it clickable.
    node['href'] ||= ''
  end

  @current_scope.add_binding(node['id'], "lambda { |target, context, id| EventBinding.new(target, context, id, #{event.inspect}, Proc.new {|event| #{content} })}")
end

#add_if_binding(node, content) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/volt/server/template_parser.rb', line 98

def add_if_binding(node, content)
	html = "<!-- $#{@binding_number} -->"

   template_name = "#{@template_parser.template_path}/#{section_name}/__template/#{@binding_number}"
   if_binding_setup = IfBindingSetup.new
   if_binding_setup.add_branch(content, template_name)
   
	@current_scope.start_if_binding(@binding_number, if_binding_setup)

	# Add the node, the binding number, then store the location where the
	# bindings for this block starts.
	@current_scope = Scope.new(@binding_number)
	@scopes << @current_scope

	@binding_number += 1
	return html
end

#add_multiple_getters(node, attribute, content) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/volt/server/template_parser.rb', line 200

def add_multiple_getters(node, attribute, content)
  case attribute
  when 'checked', 'value'
    if parts.size > 1
      # Multiple ReactiveValue's can not be passed to value or checked attributes.
      raise "Multiple bindings can not be passed to a #{attribute} binding."
    end
  end
  
  reactive_template_path = add_reactive_template(content)
  
  @current_scope.add_binding(node['id'], "lambda { |target, context, id| AttributeBinding.new(target, context, id, #{attribute.inspect}, Proc.new { ReactiveTemplate.new(context, #{reactive_template_path.inspect}) }) }")
end

#add_reactive_template(content) ⇒ Object

Returns a path to a template for the content. This can be passed into ReactiveTemplate.new, along with the current context.



216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/volt/server/template_parser.rb', line 216

def add_reactive_template(content)
  # Return a template path instead
  template_name = "__attribute/#{@binding_number}"
  full_template_path = "#{@template_parser.template_path}/#{section_name}/#{template_name}"
  @binding_number += 1

  attribute_template = Template.new(@template_parser, section_name, Nokogiri::HTML::DocumentFragment.parse(content))
  @template_parser.add_template("#{section_name}/#{template_name}", attribute_template)
  attribute_template.start_walk
  attribute_template.pull_closed_block_scopes

  return full_template_path
end

#add_single_getter(node, attribute, content) ⇒ Object



187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/volt/server/template_parser.rb', line 187

def add_single_getter(node, attribute, content)
  if attribute == 'checked' || true
    # For a checkbox, we don't want to add
    getter = content[1..-2]
  else
    # Otherwise we should combine them
    # TODO: We should make .or handle assignment
    getter = "_tmp = #{content[1..-2]}.or('') ; _tmp.reactive_manager.setter! { |val| self.#{content[1..-2]} = val } ; _tmp"
  end
  
  @current_scope.add_binding(node['id'], "lambda { |target, context, id| AttributeBinding.new(target, context, id, #{attribute.inspect}, Proc.new { #{getter} }) }")
end

#add_template(node, content) ⇒ Object



72
73
74
75
76
77
78
79
# File 'lib/volt/server/template_parser.rb', line 72

def add_template(node, content)
	html = "<!-- $#{@binding_number} --><!-- $/#{@binding_number} -->"

	@current_scope.add_binding(@binding_number, "lambda { |target, context, id| TemplateBinding.new(target, context, id, #{@template_parser.template_path.inspect}, Proc.new { [#{content}] }) }")

	@binding_number += 1
	return html
end

#add_text_binding(content) ⇒ Object

When we find a binding, we pass it’s content in here and replace it with the return value



151
152
153
154
155
156
157
158
# File 'lib/volt/server/template_parser.rb', line 151

def add_text_binding(content)
	html = "<!-- $#{@binding_number} --><!-- $/#{@binding_number} -->"

	@current_scope.add_binding(@binding_number, "lambda { |target, context, id| ContentBinding.new(target, context, id, Proc.new { #{content} }) }")

	@binding_number += 1
	return html
end

#find_by_comment(name) ⇒ Object



280
281
282
# File 'lib/volt/server/template_parser.rb', line 280

def find_by_comment(name)
  return @template.xpath("descendant::comment()[. = ' #{name} ']").first
end

#htmlObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/volt/server/template_parser.rb', line 21

def html
   if @template.respond_to?(:name) && @template.name[0] == ':'
     # Don't return the <:section> tags
     return @template.children.to_html
   else
     # if @template.class == Nokogiri::XML::NodeSet
     #   result = ''
     #   @template.each do |node|
     #     result << node.to_html
     #   end
     # else
   		result = @template.to_html
     # end
     result
   end
end

#move_nodes_to_new_template(start_node, end_node, scope) ⇒ Object



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/volt/server/template_parser.rb', line 259

def move_nodes_to_new_template(start_node, end_node, scope)
   # TODO: currently this doesn't handle spanning nodes within seperate containers.
   # so doing tr's doesn't work for some reason.
   
	start_parent = start_node.parent
	start_parent = start_parent.children if start_parent.is_a?(Nokogiri::HTML::DocumentFragment) || start_parent.is_a?(Nokogiri::XML::Element)
	start_index = start_parent.index(start_node) + 1

	end_parent = end_node.parent
	end_parent = end_parent.children if end_parent.is_a?(Nokogiri::HTML::DocumentFragment) || end_parent.is_a?(Nokogiri::XML::Element)
	end_index = end_parent.index(end_node) - 1

	move_nodes = start_parent[start_index..end_index]
	move_nodes.remove

   new_template = Template.new(@template_parser, section_name, move_nodes, scope)
   
   @template_parser.add_template("#{section_name}/__template/#{scope.outer_binding_number}", new_template)
end

#parse_component(node) ⇒ Object

We provide a quick way to render components with tags starting with a : Count the number of /‘s in the path, if we are at the root node we can ignore it, since this is the template its self. TODO: Root node might not be the template if we parsed directly without a subtemplate specifier. We need to find a good way to parse only within the subtemplate.



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
# File 'lib/volt/server/template_parser.rb', line 322

def parse_component(node)
  template_path = node.name[1..-1].gsub(':', '/')

  # Take the attributes and turn them into a hash
  attribute_hash = {}
  node.attribute_nodes.each do |attribute_node|
    content = attribute_node.value
    
    if !content.index('{')
      # passing in a string
      value = content.inspect
    elsif content =~ /^\{[^\}]+\}$/
      # Has one binding, just get it
      value = "Proc.new { #{content[1..-2]} }"
    else
      # Has multiple bindings, we need to render a template here
      attr_template_path = add_reactive_template(content)
      
      value = "Proc.new { ReactiveTemplate.new(context, #{attr_template_path.inspect}) }"
    end
    
    attribute_hash[attribute_node.name] = value
  end
  
  attributes_string = attribute_hash.to_a.map do |key, value|
    "#{key.inspect} => #{value}"
  end.join(', ')

  # Setup the arguments string, which goes to the TemplateBinding
  args_str = "#{template_path.inspect}"
  args_str << ", {#{attributes_string}}" if attribute_hash.size > 0

new_html = add_template(node, args_str)
  
  node.swap(new_html)#Nokogiri::HTML::DocumentFragment.parse(new_html))
end

#parse_html_node(node) ⇒ Object



371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/volt/server/template_parser.rb', line 371

def parse_html_node(node)
node.attribute_nodes.each do |attribute_node|
  if attribute_node.name =~ /^e\-/
      # We have an e- binding
      add_event_binding(node, attribute_node.name, attribute_node.value)

      # remove the attribute
      attribute_node.remove
	elsif attribute_node.value.match(/\{[^\}]+\}/)
      # Has bindings
		add_attribute_binding(node, attribute_node.name, attribute_node.value)

		# remove the attribute
		attribute_node.remove
	end
end    
end

#parse_textarea(node) ⇒ Object



359
360
361
362
363
364
365
366
367
368
369
# File 'lib/volt/server/template_parser.rb', line 359

def parse_textarea(node)
  # The contents of textareas should really be treated like a 
  # value= attribute.  So here we pull the content into a value attribute
  # if the textarea has bindings in the content.
  if node.inner_html =~ /\{[^\}]+\}/
    node[:value] = node.inner_html
    node.children.remove
  end
  
  parse_html_node(node)
end

#pull_closed_block_scopes(scope = @current_scope) ⇒ Object



243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/volt/server/template_parser.rb', line 243

def pull_closed_block_scopes(scope=@current_scope)
  if scope.closed_block_scopes
    scope.closed_block_scopes.each do |sub_scope|
      # Loop through any subscopes first, pull them in.
      pull_closed_block_scopes(sub_scope)
      
      # Grab everything between the start/end html comments
      start_node = find_by_comment("$#{sub_scope.outer_binding_number}")
      end_node = find_by_comment("$/#{sub_scope.outer_binding_number}")

      move_nodes_to_new_template(start_node, end_node, sub_scope)
    end
  end
end

#setup_node_id(node) ⇒ Object



160
161
162
163
164
165
166
167
# File 'lib/volt/server/template_parser.rb', line 160

def setup_node_id(node)
  id = node['id']
# First assign this node an id if it doesn't have one
unless id
	id = node['id'] = "id#{@binding_number}"
	@binding_number += 1
end
end

#start_walkObject



284
285
286
# File 'lib/volt/server/template_parser.rb', line 284

def start_walk
	walk(@template)
end

#walk(node) ⇒ Object

We implement a dom walker that can walk down the dom and spit out output html as we go



290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/volt/server/template_parser.rb', line 290

def walk(node)
	case node.type
	when 1
		# html node
     walk_html_node(node)
	when 3
		# text node
     walk_text_node(node)
	end

	node.children.each do |child|
		walk(child)
	end
end

#walk_html_node(node) ⇒ Object



305
306
307
308
309
310
311
312
313
# File 'lib/volt/server/template_parser.rb', line 305

def walk_html_node(node)
  if node.name[0] == ':' && node.path.count('/') > 1
    parse_component(node)
  elsif node.name == 'textarea'
    parse_textarea(node)
  else
    parse_html_node(node)
  end
end

#walk_text_node(node) ⇒ Object



389
390
391
392
393
394
395
396
397
398
399
400
# File 'lib/volt/server/template_parser.rb', line 389

def walk_text_node(node)
new_html = node.content.gsub(/\{([^\}]+)\}/) do |template_binding|
	add_binding(node, $1)
end

  # puts "------! #{new_html.inspect} - #{node.class.inspect} - #{node.inspect}"

  # TODO: Broke here in jruby
  node.swap(new_html)# if new_html.blank?
  
  #Nokogiri::HTML::DocumentFragment.parse(new_html))
end