Module: Zafu::Process::Ajax

Defined in:
lib/zafu/process/ajax.rb

Instance Method Summary collapse

Instance Method Details

#dom_name(context = @context) ⇒ Object

Return object id (or name). Sets name when needed. Context is passed when the parent needs to set dom_name on a child before @context is passed down.



388
389
390
# File 'lib/zafu/process/ajax.rb', line 388

def dom_name(context = @context)
  @dom_name ||= unique_name(context)
end

#expand_with_finder(finder) ⇒ Object

This method process a list and handles building the necessary templates for ajax ‘add’.



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
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
# File 'lib/zafu/process/ajax.rb', line 10

def expand_with_finder(finder)
  @context.delete(:make_form) # Do not propagate.
  return super unless finder[:class].kind_of?(Array)

  # reset scope
  @context[:saved_template] = nil

  # Get the block responsible for rendering each elements in the list
  each_block = descendant('each')
  add_block  = descendant('add')
  form_block = descendant('form') || each_block
  edit_block = descendant('edit')


  # Should 'edit' and 'add' auto-publish ?
  publish_after_save = (form_block && form_block.params[:publish]) ||
                       (edit_block && edit_block.params[:publish])

  # class name for create form
  if class_name = (add_block  &&  add_block.params[:klass]) ||
                  (form_block && form_block.params[:klass])
    unless klass = get_class(class_name)
      return parser_error("Invalid class '#{class_name}'")
    end
  else
    klass = finder[:class].first
  end

  if need_ajax?(each_block)
    # 1. Render inline
    #                                                                                                                 assign [] to var
    out "<% if (#{var} = #{finder[:method]}) || (#{node}.#{finder[:class].first <= Comment ? "can_comment?" : "can_write?"} && #{var}=[]) %>"
    # The list is not empty or we have enough rights to add new elements.

    # New node context.
    open_node_context(finder, :node => self.node.move_to(var, finder[:class])) do
      # Pagination count and other contextual variables exist here.

      tmplt_node = self.node.move_to(var, finder[:class])
      # Own scope
      node.dom_prefix = dom_name
      tmplt_node.dom_prefix = dom_name

      # INLINE ==========
      out wrap(
        expand_with(
          :in_if              => false,
          # 'r_add' needs the form when rendering. Send with :form.
          :form               => form_block,
          :publish_after_save => publish_after_save,
          # Do not render the form block directly: let [add] do this.
          :ignore             => ['form'],
          :klass              => klass
        )
      )

      # Render 'else' clauses
      else_clauses = expand_with(
        :in_if => true,
        :only  => ['elsif', 'else'],
        :markup => @markup
      )

      # 2. Save 'each' template
      store_block(each_block, :node => tmplt_node)

      # 3. Save 'form' template
      cont = {
        :saved_template     => form_url(tmplt_node.dom_prefix),
        :klass              => klass,
        :make_form          => each_block == form_block,
        # Used to get parameters like 'publish', 'done', 'after'
        :add                => add_block,
        :publish_after_save => publish_after_save,
        :new_keys           => {:parent_id => '@node.parent_zip'}
      }

      store_block(form_block, cont)
    end
    out "<% end %>"
  else
    super
  end

  # out wrap(expand_with(:node => node.move_to(var, finder[:class]), :in_if => true))


  #query = opts[:query]
  #
  #
  #if need_ajax?
  #  new_dom_scope
  #  # ajax, build template. We could merge the following code with 'r_block'.
  #
  #  # FORM ============
  #  if each_block != form_block
  #    form = expand_block(form_block, :klass => klass, :add=>add_block, :publish_after_save => publish_after_save, :saved_template => true)
  #  else
  #    form = expand_block(form_block, :klass => klass, :add=>add_block, :make_form=>true, :publish_after_save => publish_after_save, :saved_template => true)
  #  end
  #  out helper.save_erb_to_url(form, form_url)
  #else
  #  # no form, render, edit and add are not ajax
  #  if descendant('add') || descendant('add_document')
  #    out "<% if (#{list_var} = #{list_finder}) || (#{node}.#{node.will_be?(Comment) ? "can_comment?" : "can_write?"} && #{list_var}=[]) %>"
  #  elsif list_finder != 'nil'
  #    out "<% if #{list_var} = #{list_finder} %>"
  #  else
  #    out "<% if nil %>"
  #  end
  #
  #
  #  out render_html_tag(expand_with(:list=>list_var, :in_if => false))
  #  out expand_with(:in_if=>true, :only=>['elsif', 'else'], :html_tag => @html_tag, :html_tag_params => @html_tag_params)
  #  out "<% end %>"
  #end
end

#form_url(dom_prefix = node.dom_prefix) ⇒ Object



381
382
383
# File 'lib/zafu/process/ajax.rb', line 381

def form_url(dom_prefix = node.dom_prefix)
  template_url(dom_prefix) + '_form'
end

#get_unique_name(key, own_id = false) ⇒ Object



398
399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/zafu/process/ajax.rb', line 398

def get_unique_name(key, own_id = false)
  @next_name_index ||= {}
  if @next_name_index[key]
    @next_name_index[key] += 1
    key + @next_name_index[key].to_s
  elsif own_id
    @next_name_index[key] = 0
    key
  else
    @next_name_index[key] = 1
    key + '1'
  end
end

#need_dom_id?Boolean

Return true if we need to insert the dom id for this element.

Returns:

  • (Boolean)


372
373
374
# File 'lib/zafu/process/ajax.rb', line 372

def need_dom_id?
  @context[:form] || @params[:sortable] || child['unlink'] || (single_child_method && single_child_method == child['drop'])
end

#public_descendantsObject

Block visibility of descendance with ‘do_list’.



353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/zafu/process/ajax.rb', line 353

def public_descendants
  all = super
  if ['context', 'each', 'block'].include?(method)
    # do not propagate 'form',etc up
    all.reject do |k,v|
      # FIXME: Zena leakage
      ['form','unlink', 'count'].include?(k)
    end
  elsif ['if', 'case'].include?(method) || (method =~ /^[A-Z]/)
    # conditional
    all.reject do |k,v|
      ['else', 'elsif', 'when'].include?(k)
    end
  else
    all
  end
end

#r_addObject



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
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
# File 'lib/zafu/process/ajax.rb', line 228

def r_add
  return parser_error("Should not be called from within 'each'") if parent.method == 'each'
  return parser_error("Should not be called outside list context") unless node.list_context?
  return '' if @context[:make_form]

  if node.will_be?(Comment)
    out "<% if #{node.up(Node)}.can_comment? %>"
  else
    out "<% if #{node.up(Node)}.can_write? %>"
  end

  unless descendant('add_btn')
    # Add a descendant between self and blocks. ==> add( add_btn(blocks) )
    blocks = @blocks.dup
    @blocks = []
    add_btn = make(:void, :method => 'add_btn', :params => @params.dup, :text => '')
    add_btn.blocks = blocks
    @all_descendants = nil
  end

  if @context[:form]
    # ajax add
    @markup.set_id("#{node.dom_prefix}_add")
    @markup.append_param(:class, 'btn_add')

    if @params[:focus]
      focus = "$(\"#{node.dom_prefix}_#{@params[:focus]}\").focus();"
    else
      focus = "$(\"#{node.dom_prefix}_form_t\").focusFirstElement();"
    end

    # Expand 'add' block
    out wrap("#{expand_with(:onclick=>"[\"#{node.dom_prefix}_add\", \"#{node.dom_prefix}_0\"].each(Element.toggle);#{focus}return false;")}")

    klass = @context[:klass] || node.single_class

    # New object to render form.
    new_node = node.move_to("#{var}_new", klass, :new_keys => {})


    if new_node.will_be?(Node)
      # FIXME: BUG if we set <r:form klass='Post'/> the user cannot select class with menu...

      if @context[:saved_template]
        parent_id = "#{node}.parent_zip"
      else
        parent_id = "#{node(Node)}.zip"
      end

      new_node.opts[:new_keys]['parent_id'] = parent_id

      # FIXME: inspect '@context[:form]' to see if it contains v_klass ?
      out "<% if #{new_node} = secure(Node) { Node.new_node('class' => '#{new_node.klass}', 'parent_id' => #{parent_id}) } %>"
      # if node.will_be?(Node)
      #   # Nested contexts:
      #   # 1. @node
      #   # 2. var1 = @node.children
      #   # 3. var1_new = Node.new
      #   if node.opts[:new_record] || @context[:saved_template]
      #     if @context[:saved_template] || !@context[:in_add]
      #       # TODO: we should not add parent_id on every saved_template. Why is this needed ?
      #       parent_id = "#{node}.parent_zip"
      #     else
      #       # We are in var2_new
      #       parent_id = "#{node.up(Node)}.zip"
      #     end
      #
      #     hidden_fields['node[parent_id]'] = "<%= #{parent_id} %>"
      #   end
      # els
    else
      out "<% if #{new_node} = #{new_node.class_name}.new %>"
    end

    form_block = @context[:form]

    # Expand (inline) 'form' block
    out expand_block(form_block,
      # Needed in form to be able to return the result
      :template_url => template_url(node.dom_prefix),
      # Used to avoid wrong dom_id in hidden form. Should not be
      # necessary but it's hard to fix when node changes a lot (drop in add).
      :dom_prefix   => node.dom_prefix,
      # Used to add needed hidden fields in form
      :in_add       => true,
      # Used to get parameters like 'publish' or 'klass'
      :add          => self,
      # Transform 'each' block into a form
      :make_form    => form_block.method == 'each',
      # Node context = new node
      :node         => new_node
    )
    out "<% end %>"
  else
    # no ajax
    @markup.append_param(:class, 'btn_add') if @markup.tag
    out wrap(expand_with)
  end
  out "<% end %>"
end

#r_add_btnObject



329
330
331
332
333
# File 'lib/zafu/process/ajax.rb', line 329

def r_add_btn
  default = node.will_be?(Comment) ? _("btn_add_comment") : _("btn_add")

  out "<a href='javascript:void(0)' onclick='#{@context[:onclick]}'>#{text_for_link(default)}</a>"
end

#r_blockObject

Store a context as a sub-template that can be used in ajax calls



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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/zafu/process/ajax.rb', line 129

def r_block
  if parent.method == 'each' && @method == parent.single_child_method
    # Block stored in 'each', do nothing
    # What happens when this is used as remote target ?
    return expand_with
  end

  @markup.done = false

  if @context[:block] == self
    # Storing our block template
    #node.dom_prefix = dom_name
    @markup.set_id(node.dom_id(:list => false))
    @markup.set_dyn_param(:"data-z", "<%= #{node}.zip %>")
    # Elements inside the block should render as normal (not transforming forms into remote
    # forms or things like this).
    expand_with(:template_url => nil)
  elsif @context[:saved_template]
    # already in a parent's store operation. Reset scope and simply render inline elements
    # reset scope
    with_context(:node => node.dup, :saved_template => nil) do
      node.saved_dom_id = nil
      node.dom_prefix = dom_name
      @markup.set_id(node.dom_id(:list => false))
      expand_with
    end
  else
    # Since we are using ajax, we will need this object to have an ID set and
    # have its own template_url and such.
    with_context(:node => node.dup, :saved_template => nil) do
      # reset scope. We only keep current id when we are called from
      # r_drop.
      @markup = @markup.dup
      @markup.set_id(nil)
      node.saved_dom_id = nil
      # our own domain
      node.dom_prefix = dom_name

      # 1. inline
      # Set id with the current node context (<%= var1.zip %>).
      @markup.set_id(node.dom_id(:list => false))
      if node.dom_id(:list => false) != node.dom_prefix
        @markup.set_param(:"data-t", node.dom_prefix)
      end
      @markup.set_dyn_param(:"data-z", "<%= #{node}.zip %>")

      out expand_with
      # 2. store template
      # will wrap with @markup
      store_block(self, :ajax_action => 'show')

      if edit_block = descendant('edit')
        form_block = descendant('form') || self

        publish_after_save = form_block.params[:publish] ||
                             (edit_block && edit_block.params[:publish])

        # 3. store form
        cont = {
          :saved_template     => form_url(node.dom_prefix),
          :make_form          => self == form_block,
          :publish_after_save => publish_after_save,
          :ajax_action        => 'edit',
        }

        store_block(form_block, cont)
      end
    end
  end
end

#r_cancelObject



224
225
226
# File 'lib/zafu/process/ajax.rb', line 224

def r_cancel
  r_edit
end

#r_eachObject



335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/zafu/process/ajax.rb', line 335

def r_each
  if @context[:saved_template]
    # render to start a saved template
    node.saved_dom_id = "\#{ndom_id(#{node})}"
    node.dom_prefix = dom_name unless node.raw_dom_prefix
    node.propagate_dom_scope!
    @markup.set_id(node.dom_id)

    options = form_options
    @markup.set_param(:style, options[:style]) if options[:style]

    out wrap(expand_with)
  else
    super
  end
end

#r_editObject



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/zafu/process/ajax.rb', line 201

def r_edit
  # ajax
  if cancel = @context[:form_cancel]
    # cancel button
    out cancel
  else
    # edit button

    # TODO: show 'reply' instead of 'edit' in comments if visitor != author
    block = ancestor(%w{each block})

    # These parameters are detected by r_block and set in form.
    # removed so they do not polute link
    @params.delete(:publish)
    @params.delete(:cancel)
    @params.delete(:tcancel)

    link = wrap(make_link(:default_text => _('edit'), :update => block, :action => 'edit'))

    out "<% if #{node}.can_write? %>#{link}<% end %>"
  end
end

#save_stateObject



4
5
6
# File 'lib/zafu/process/ajax.rb', line 4

def save_state
  super.merge(:@markup => @markup.dup)
end

#template_url(dom_prefix = node.dom_prefix) ⇒ Object

Unique template_url, ending with dom_id



377
378
379
# File 'lib/zafu/process/ajax.rb', line 377

def template_url(dom_prefix = node.dom_prefix)
  "#{root.options[:root]}/#{dom_prefix}"
end

#unique_name(context = @context) ⇒ Object

Return a different name on each call



393
394
395
396
# File 'lib/zafu/process/ajax.rb', line 393

def unique_name(context = @context)
  base = @name || context[:name] || 'list'
  root.get_unique_name(base, base == @name).gsub(/[^\d\w\/]/,'_')
end