# HG changeset patch
# User Sylvain Thénault <sylvain.thenault@logilab.fr>
# Date 1296492492 -3600
#      Mon Jan 31 17:48:12 2011 +0100
# Branch stable
# Node ID cbd166b57b9c0adb45d10419dbd746fcc12652e4
# Parent  0e7cd8d996b7fa590a2baf243e3f03b02255e400
use new cw 3.10.8 APIs to simplify inline form handling

diff --git a/__pkginfo__.py b/__pkginfo__.py
--- a/__pkginfo__.py
+++ b/__pkginfo__.py
@@ -19,7 +19,7 @@
            'Programming Language :: JavaScript',
 ]
 
-__depends__ = {'cubicweb': '>= 3.10.0'}
+__depends__ = {'cubicweb': '>= 3.10.8'}
 
 
 # packaging ###
diff --git a/data/cubes.comment.js b/data/cubes.comment.js
--- a/data/cubes.comment.js
+++ b/data/cubes.comment.js
@@ -9,50 +9,45 @@
  * It calls the [add|eid]_comment method on the jsoncontroller and [re]load
  * only the view for the added or edited comment
  */
-function processComment(eid, cancel, creation, parentcreated) {
-    var divId = 'comment' + eid + 'Slot';
-    var divNode = jQuery('#'+divId);
-    var textarea = divNode.find('textarea')[0];
-    if (!cancel) {
-	validateForm('commentForm' + eid, null,
-		     function(result, formid, cbargs) {
-			 var neweid = result[2].eid;
-			 if (creation) {
-			     var commentNode = $('#comment'+ eid);
-			     var ul = null;
-			     if (!commentNode.length) {
-				 commentNode = $('#commentsection' + eid);
-				 // we are adding a comment to the top level
-				 // entity, reload the whole component
-				 if (parentcreated) {
-				     // in this case, neweid is the eid of top
-				     // level entity (and eid given as argument
-				     // a fake eid (e.g. A)
-				     eid = neweid;
-				 }
-				 var params = ajaxFuncArgs('render', null, 'ctxcomponents', 'commentsection', eid);
-				 commentNode.loadxhtml('json', params, null, 'swap', true);
-				 return
-			     }
-			     ul = commentNode.find('> ul:first');
-			     if (!ul.length) {
-				 ul = jQuery(UL({'class': 'section'}));
-				 commentNode.append(ul);
-			     }
-			     ul.append(LI({'id': 'comment'+ neweid, 'class': 'comment'},
-					  DIV({'id': 'comment'+ neweid + 'Div'})));
-			     divNode.remove();
-			 }
-			 var params = ajaxFuncArgs('render', null, 'views', 'treeitem', neweid);
-			 $('#comment' + neweid + 'Div').loadxhtml('json', params, null, null, true);
-		     });
-    } else {
-	// comment cancelled, close div holding the form
-        divNode.remove();
-	// on edition, show back the comment's content
-	if (!creation) {
-	    jQuery('#comment' + eid + 'Div div').show();
-	}
+function processComment(eid, creation, parentcreated, context) {
+    validateForm(
+	'commentsForm' + eid, null,
+	function(result, formid, cbargs) {
+	    var neweid = result[2].eid;
+	    if (creation) {
+		var $commentNode = $('#comment'+ eid);
+		if (!$commentNode.length) {
+		    if (parentcreated) {
+			// the top level entity has just been created, reload
+			// the whole components section
+			reloadCtxComponentsSection(context, neweid, eid)
+		    } else {
+			// only reload the comments component
+			reload('commentsection' + eid, 'commentsection',
+			       'ctxcomponents', null, eid);
+		    }
+		    return ;
+		}
+		var ul = $commentNode.find('> ul:first');
+		if (!ul.length) {
+		    ul = $(UL({'class': 'section'}));
+		    $commentNode.append(ul);
+		}
+		ul.append(LI({'id': 'comment'+ neweid, 'class': 'comment'},
+			     DIV({'id': 'comment'+ neweid + 'Div'})));
+		$('#comment' + eid + 'Slot').remove();
+	    }
+	    var params = ajaxFuncArgs('render', null, 'views', 'treeitem', neweid);
+	    $('#comment' + neweid + 'Div').loadxhtml('json', params, null, null, true);
+	});
+}
+
+function cancelCommentEdition(eid, creation) {
+    // comment cancelled, close div holding the form
+    $('#comment' + eid + 'Slot').remove();
+    // on edition, show back the comment's content
+    if (!creation) {
+	$('#comment' + eid + 'Div div').show();
     }
 }
 
diff --git a/views.py b/views.py
--- a/views.py
+++ b/views.py
@@ -21,11 +21,12 @@
                                 match_kwargs, match_form_params,
                                 partial_relation_possible, traced_selection)
 from cubicweb.view import EntityView
-from cubicweb.uilib import rql_for_eid, cut, safe_cut
+from cubicweb.uilib import rql_for_eid, cut, safe_cut, js
 from cubicweb.mixins import TreeViewMixIn
 from cubicweb.web import stdmsgs, uicfg, component, form, formwidgets as fw
 from cubicweb.web.action import LinkToEntityAction, Action
-from cubicweb.web.views import primary, baseviews, xmlrss, basecontrollers, treeview
+from cubicweb.web.views import (primary, baseviews, xmlrss, basecontrollers,
+                                treeview, ajaxedit)
 
 _afs = uicfg.autoform_section
 _afs.tag_object_of(('*', 'comments', '*'), formtype='main', section='hidden')
@@ -204,8 +205,6 @@
     __regid__ = 'editcommentform'
     __select__ = is_instance('Comment')
 
-    jsfunc = "processComment(%s, %s, false, %s)"
-
     def entity_call(self, entity):
         self.comment_form(entity)
 
@@ -220,31 +219,13 @@
         self._cw.add_js(('cubicweb.edition.js', 'cubes.comment.js'))
         if self._cw.cnx.anonymous_connection:
             self.propose_to_login()
-        # hack to avoid tabindex conflicts caused by Ajax requests
-        self._cw.next_tabindex = count(20).next
-        jseid = json_dumps(commented.eid)
-        existingparent = newcomment is None or commented.has_eid()
-        buttons = [fw.Button(onclick=self.jsfunc % (jseid, 'false', existingparent and 'false' or 'true')),
-                   fw.Button(stdmsgs.BUTTON_CANCEL,
-                             onclick=self.jsfunc % (jseid, 'true', 'null'))]
-        fvreg = self._cw.vreg['forms']
-        formvalues = {}
-        if newcomment is not None: # creation
-            formvalues['comments'] = commented.eid
-        if existingparent: # creation / edition
-            # use formtype=inlined to avoid viewing the relation edition section
-            form = fvreg.select('edition', self._cw, entity=newcomment or commented,
-                                domid='commentForm%s' % commented.eid,
-                                form_buttons=buttons,
-                                formtype='inlined')
-        else: # creation of both commented and comment entities
-            form = fvreg.select('composite', self._cw, form_buttons=buttons,
-                                domid='commentForm%s' % commented.eid,
-                                form_renderer_id='default')
-            form.add_subform(fvreg.select('edition', self._cw, entity=commented,
-                                          mainform=False, mainentity=True))
-            form.add_subform(fvreg.select('edition', self._cw, entity=newcomment,
-                                          mainform=False))
+        entity = newcomment or commented
+        okjs = js.processComment(commented.eid, not entity.has_eid(),
+                                 not (newcomment is None or commented.has_eid()),
+                                 self.cw_extra_kwargs.get('context'))
+        canceljs = js.cancelCommentEdition(commented.eid, not entity.has_eid())
+        form, formvalues = ajaxedit.ajaxCompositeForm(
+            commented, newcomment, 'comments', okjs, canceljs)
         self.w(u'<div id="comment%sSlot">' % commented.eid)
         form.render(w=self.w, formvalues=formvalues,
                     main_form_title=u'', display_label=False)
@@ -256,12 +237,10 @@
     __select__ = (relation_possible('comments', 'object', 'Comment', 'add')
                   | match_form_params('etype'))
 
-    jsfunc = "processComment(%s, %s, true, %s)"
-
     def call(self, **kwargs):
         if self.cw_rset is None:
             entity = self._cw.vreg['etypes'].etype_class(self._cw.form['etype'])(self._cw)
-            entity.eid = self._cw.varmaker.next()
+            entity.eid = self._cw.form['tempEid']
             self.entity_call(entity)
         else:
             super(InlineAddCommentFormView, self).call(**kwargs)
@@ -303,17 +282,8 @@
                     self._cw.view('tree', rset, row=i, w=w)
                 w(u'</ul>')
         if addcomment is not None:
-            w(u'<div id="comment%sHolder"></div>' % entity.eid)
-            params = self.cw_extra_kwargs.copy()
-            params.pop('view', None)
-            params.pop('context', None)
-            if entity.has_eid():
-                params['eid'] = entity.eid
-            else:
-                params['etype'] = entity.__regid__
-            url = req.ajax_replace_url(
-                'comment%sHolder' % entity.eid, vid='addcommentform', **params)
-            w(u' (<a href="%s">%s</a>)' % (xml_escape(url), req._(addcomment.title)))
+            url = self.lazy_view_holder(w, entity, 'addcommentform')
+            w(u' <span>(<a href="%s">%s</a>)</span>' % (xml_escape(url), req._(addcomment.title)))
 
 
 class UserLatestCommentsSection(component.EntityCtxComponent):