Module: Zafu::Process::Ajax

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

Instance Method Summary collapse

Instance Method Details

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

def expand_with_finder(finder)
  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
  klass       = (add_block  &&  add_block.params[:klass]) ||
                (form_block && form_block.params[:klass])

  if need_ajax?(each_block)
    # We need to build the templates for ajax rendering.

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

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

      # 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
      @markup.done = false
      out wrap(
        expand_with(
          :in_if => true,
          :only  => ['elsif', 'else']
        )
      )

      # 2. Save 'each' template
      store_block(each_block, :node => self.node.move_to(var, finder[:class])) #, :klass => klass) # do we need klass here ?

      # 3. Save 'form' template
      cont = {
        :saved_template     => form_url(node.dom_prefix),
        :klass              => klass,
        :make_form          => each_block == form_block,
        :publish_after_save => publish_after_save,
      }

      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



300
301
302
# File 'lib/zafu/process/ajax.rb', line 300

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

#get_unique_name(key, own_id = false) ⇒ Object



310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/zafu/process/ajax.rb', line 310

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)


284
285
286
# File 'lib/zafu/process/ajax.rb', line 284

def need_dom_id?
  @context[:form] || descendant('unlink') || descendant('drop')
end

#public_descendantsObject

Block visibility of descendance with ‘do_list’.



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/zafu/process/ajax.rb', line 267

def public_descendants
  all = super
  if ['context', 'each', 'block'].include?(self.method)
    # do not propagate 'form',etc up
    all.reject do |k,v|
      ['form','unlink'].include?(k)
    end
  elsif ['if', 'case'].include?(self.method)
    all.reject do |k,v|
      ['else', 'elsif', 'when'].include?(k)
    end
  else
    all
  end
end

#r_addObject



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

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
    remove_instance_variable(:@all_descendants)
  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}_form\"].each(Element.toggle);#{focus}return false;")}")

    # New object to render form.
    # FIXME: use 'klass' param in r_add or r_form instead of current list content.
    new_node = node.move_to("#{var}_new", [node.klass].flatten.first)

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

      # FIXME: inspect '@context[:form]' to see if it contains v_klass ?
      out "<% if #{new_node} = secure(Node) { Node.new_from_class('#{new_node.class_name}') } -%>"
    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),
      # ??
      :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



247
248
249
250
251
# File 'lib/zafu/process/ajax.rb', line 247

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

  out "<a href='#' 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



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

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

  # Since we are using ajax, we will need this object to have an ID set.
  set_dom_prefix

  @markup.done = false

  if @context[:block] == self
    # Storing template (called from within store_block)
    # Set id with the template's node context (<%= @node.zip %>).
    @markup.set_id(node.dom_id(:list => false))
    expand_with
  else
    # 1. store template
    # will wrap with @markup
    store_block(self)

    # 2. render
    # Set id with the current node context (<%= var1.zip %>).
    @markup.set_id(node.dom_id(:list => false))
    out expand_with
  end
end

#r_cancelObject



172
173
174
# File 'lib/zafu/process/ajax.rb', line 172

def r_cancel
  (@context[:form_options] || {})[:form_cancel]
end

#r_eachObject



253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/zafu/process/ajax.rb', line 253

def r_each
  if @context[:saved_template]
    # render to start a saved template
    options = form_options
    @markup.set_id(options[:id]) if options[:id]
    @markup.set_param(:style, options[:style]) if options[:style]

    out wrap(expand_with)
  else
    super
  end
end

#r_editObject



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/zafu/process/ajax.rb', line 149

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

    # TODO: show 'reply' instead of 'edit' in comments if visitor != author
    each_block = ancestor('each')

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

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

  #if @context[:template_url]
  #else
  #  # FIXME: we could link to some html page to edit the item.
  #  ""
  #end
end

#save_stateObject



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

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

#set_dom_prefix(node = self.node) ⇒ Object

Set a unique DOM prefix to build unique ids in the page.



289
290
291
292
293
# File 'lib/zafu/process/ajax.rb', line 289

def set_dom_prefix(node = self.node)
  @name ||= unique_name
  # TODO: should rebuild descendants list in parents...
  node.dom_prefix = @name
end

#template_url(dom_prefix = node.dom_prefix) ⇒ Object

Unique template_url, ending with dom_id



296
297
298
# File 'lib/zafu/process/ajax.rb', line 296

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

#unique_nameObject

Return a different name on each call



305
306
307
308
# File 'lib/zafu/process/ajax.rb', line 305

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