# HG changeset patch
# User Sylvain Thénault <sylvain.thenault@logilab.fr>
# Date 1296132468 -3600
#      Thu Jan 27 13:47:48 2011 +0100
# Branch stable
# Node ID 0e7cd8d996b7fa590a2baf243e3f03b02255e400
# Parent  1af5afd11b85d36b5c0791d3ca8e2d0c6915f79e
refactor and fix ability to add comment to a not yet created entity

Which has been broken with cw 3.10 refactoring. This also fix and incoherent
display pb in the regular cases: when adding first comment, it wasn't not
displayed similarly right after the ajax call and after a page reload.

diff --git a/data/cubes.comment.js b/data/cubes.comment.js
--- a/data/cubes.comment.js
+++ b/data/cubes.comment.js
@@ -1,14 +1,15 @@
 /*
  *  :organization: Logilab
- *  :copyright: 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+ *  :copyright: 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
  *  :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
  */
 
 /* this function is called on inlined-comment editions
+ *
  * 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) {
+function processComment(eid, cancel, creation, parentcreated) {
     var divId = 'comment' + eid + 'Slot';
     var divNode = jQuery('#'+divId);
     var textarea = divNode.find('textarea')[0];
@@ -20,23 +21,30 @@
 			     var commentNode = $('#comment'+ eid);
 			     var ul = null;
 			     if (!commentNode.length) {
-				 // we are adding a comment to the top level entity
 				 commentNode = $('#commentsection' + eid);
-				 klass = 'comment';
-			     } else {
-				 klass = 'section';
+				 // 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': klass}));
+				 ul = jQuery(UL({'class': 'section'}));
 				 commentNode.append(ul);
 			     }
 			     ul.append(LI({'id': 'comment'+ neweid, 'class': 'comment'},
 					  DIV({'id': 'comment'+ neweid + 'Div'})));
 			     divNode.remove();
 			 }
-			 var form = ajaxFuncArgs('render', null, 'views', 'treeitem', neweid);
-			 $('#comment' + neweid + 'Div').loadxhtml('json', form, null, null, true);
+			 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
diff --git a/views.py b/views.py
--- a/views.py
+++ b/views.py
@@ -1,7 +1,7 @@
 """Specific views and actions for application using the Comment entity type
 
 :organization: Logilab
-:copyright: 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+:copyright: 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
 :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
 """
 from __future__ import with_statement
@@ -204,7 +204,7 @@
     __regid__ = 'editcommentform'
     __select__ = is_instance('Comment')
 
-    jsfunc = "processComment(%s, %s, false)"
+    jsfunc = "processComment(%s, %s, false, %s)"
 
     def entity_call(self, entity):
         self.comment_form(entity)
@@ -223,14 +223,15 @@
         # hack to avoid tabindex conflicts caused by Ajax requests
         self._cw.next_tabindex = count(20).next
         jseid = json_dumps(commented.eid)
-        buttons = [fw.Button(onclick=self.jsfunc % (jseid, 'false')),
+        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'))]
+                             onclick=self.jsfunc % (jseid, 'true', 'null'))]
         fvreg = self._cw.vreg['forms']
         formvalues = {}
         if newcomment is not None: # creation
             formvalues['comments'] = commented.eid
-        if newcomment is None or commented.has_eid(): # creation / edition
+        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,
@@ -241,9 +242,9 @@
                                 domid='commentForm%s' % commented.eid,
                                 form_renderer_id='default')
             form.add_subform(fvreg.select('edition', self._cw, entity=commented,
-                                          mainform=False))
+                                          mainform=False, mainentity=True))
             form.add_subform(fvreg.select('edition', self._cw, entity=newcomment,
-                                 mainform=False))
+                                          mainform=False))
         self.w(u'<div id="comment%sSlot">' % commented.eid)
         form.render(w=self.w, formvalues=formvalues,
                     main_form_title=u'', display_label=False)
@@ -255,7 +256,7 @@
     __select__ = (relation_possible('comments', 'object', 'Comment', 'add')
                   | match_form_params('etype'))
 
-    jsfunc = "processComment(%s, %s, true)"
+    jsfunc = "processComment(%s, %s, true, %s)"
 
     def call(self, **kwargs):
         if self.cw_rset is None:
@@ -295,16 +296,12 @@
                   'C comments X, C creation_date CD, C content CC, C content_format CCF, ' \
                   'C created_by U?, U login UL, U firstname UF, U surname US, X eid %(x)s'
             rset = req.execute(rql, {'x': entity.eid})
-        else:
-            rset = None
-        if not (rset or addcomment):
-            return
-        if rset.rowcount:
-            w(u'<h4>%s</h4>' % (req._('Comment_plural')))
-            w(u'<ul class="comment">')
-            for i in xrange(rset.rowcount):
-                self._cw.view('tree', rset, row=i, w=w)
-            w(u'</ul>')
+            if rset.rowcount:
+                w(u'<h4>%s</h4>' % (req._('Comment_plural')))
+                w(u'<ul class="comment">')
+                for i in xrange(rset.rowcount):
+                    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()