From 6b040c7b4a2bf2335a5ca2915d10e8ae25d87120 Mon Sep 17 00:00:00 2001
From: Dan Hansen <mokker1234@gmail.com>
Date: Mon, 22 Aug 2011 19:28:46 -0500
Subject: [PATCH] clean up websocket receiver, add specs to content updater

---
 app/views/aspects/_aspect_stream.haml     |   4 +-
 app/views/aspects/_no_posts_message.haml  |   2 +-
 app/views/comments/create.js.erb          |   5 +-
 app/views/likes/update.js.erb             |   2 +-
 public/javascripts/content-updater.js     |  27 +++-
 public/javascripts/web-socket-receiver.js | 170 ++++------------------
 public/stylesheets/sass/application.sass  |   4 -
 spec/javascripts/content-updater-spec.js  |  63 ++++++++
 8 files changed, 119 insertions(+), 158 deletions(-)

diff --git a/app/views/aspects/_aspect_stream.haml b/app/views/aspects/_aspect_stream.haml
index b086f31274..50936ef706 100644
--- a/app/views/aspects/_aspect_stream.haml
+++ b/app/views/aspects/_aspect_stream.haml
@@ -17,9 +17,7 @@
       = @aspects.to_sentence
 
 = render 'shared/publisher', :selected_aspects => @aspects, :aspect_ids => aspect_ids, :aspect => @aspect
-
-- if posts.length == 0
-  = render 'aspects/no_posts_message'
+= render 'aspects/no_posts_message'
 
 - if current_user.contacts.size < 2
   = render 'aspects/no_contacts_message'
diff --git a/app/views/aspects/_no_posts_message.haml b/app/views/aspects/_no_posts_message.haml
index 3891b99b40..3c9ca18aad 100644
--- a/app/views/aspects/_no_posts_message.haml
+++ b/app/views/aspects/_no_posts_message.haml
@@ -2,5 +2,5 @@
 -#   licensed under the Affero General Public License version 3 or later.  See
 -#   the COPYRIGHT file.
 
-#no_posts.empty_message
+#no_posts.hidden.empty_message
   = t('.start_talking')
diff --git a/app/views/comments/create.js.erb b/app/views/comments/create.js.erb
index e4891b2da5..a416076368 100644
--- a/app/views/comments/create.js.erb
+++ b/app/views/comments/create.js.erb
@@ -1,7 +1,6 @@
-WebSocketReceiver.processComment("<%= @comment.post.guid %>", 
+ContentUpdater.addCommentToPost("<%= @comment.post.guid %>",
    "<%= @comment.guid%>",
-   "<%= escape_javascript(render(:partial => 'comments/comment', :locals => { :comment => @comment, :person => current_user.person}))%>",
-   false);
+   "<%= escape_javascript(render(:partial => 'comments/comment', :locals => { :comment => @comment, :person => current_user.person}))%>");
 
 Diaspora.page
   .stream
diff --git a/app/views/likes/update.js.erb b/app/views/likes/update.js.erb
index 439b93ce93..39e6bc854c 100644
--- a/app/views/likes/update.js.erb
+++ b/app/views/likes/update.js.erb
@@ -1,2 +1,2 @@
 $(".like_action", "#<%=@like.target.guid%>").first().html("<%= escape_javascript(like_action(@like.target))%>");
-WebSocketReceiver.processLike("<%=@like.target.guid%>", "<%= escape_javascript(render("likes/likes_container", :target_id => @like.target_id, :likes_count => @like.target.likes_count, :target_type => @like.target_type)) %>");
+ContentUpdater.addLikesToPost("<%=@like.target.guid%>", "<%= escape_javascript(render("likes/likes_container", :target_id => @like.target_id, :likes_count => @like.target.likes_count, :target_type => @like.target_type)) %>");
diff --git a/public/javascripts/content-updater.js b/public/javascripts/content-updater.js
index 158eb93621..3069750352 100644
--- a/public/javascripts/content-updater.js
+++ b/public/javascripts/content-updater.js
@@ -23,13 +23,32 @@ var ContentUpdater = {
     }
   },
 
-  addLikesToPost: function(postGUID, html) {
-    var post = $("#" + postGUID);
+  removePostFromStream: function(postGUID) {
+    $("#" + postGUID).fadeOut(400, function() {
+      $(this).remove();
+    });
+
+    if(!$("#main_stream .stream_element").length) {
+      $("#no_posts").removeClass("hidden");
+    }
+  },
+
+  addCommentToPost: function(postGUID, commentGUID, html) {
+    var post = $("#" + postGUID),
+      comments = $("ul.comments", post);
+
+    if($("#" + commentGUID, post).length) { return; }
 
-    $(".likes_container", post)
+    $(html).appendTo(comments).fadeIn("fast");
+
+    Diaspora.page.timeAgo.updateTimeAgo();
+    Diaspora.page.directionDetector.updateBinds();
+  },
+
+  addLikesToPost: function(postGUID, html) {
+    $(".likes_container", "#" + postGUID)
       .fadeOut("fast")
       .html(html)
       .fadeIn("fast");
   }
-
 };
diff --git a/public/javascripts/web-socket-receiver.js b/public/javascripts/web-socket-receiver.js
index ec00e0926d..367be8c3a1 100644
--- a/public/javascripts/web-socket-receiver.js
+++ b/public/javascripts/web-socket-receiver.js
@@ -1,146 +1,41 @@
-var WebSocketReceiver = {
+var WSR = WebSocketReceiver = {
   initialize: function(url) {
-    var ws = new WebSocket(url);
-    WSR.socket = ws;
+    WSR.socket = new WebSocket(url);
 
-    //Attach onmessage to websocket
-    ws.onmessage = WSR.onMessage;
-    ws.onclose = function() {
-      if (websocket_enabled) {
-       /* Diaspora.widgets.notifications.showNotification({
-          html: '<div class="notification">' +
-              Diaspora.I18n.t("web_sockets.disconnected") +
-            '</div>',
-          incrementCount: false
-        }); TODO:figure out why this fires so often */
-
-        WSR.debug("socket closed");
-      }
-    };
-    ws.onopen = function() {
-      ws.send(location.pathname);
-      WSR.debug("connected...");
+    WSR.socket.onmessage = WSR.onMessage;
+    WSR.socket.onopen = function() {
+      WSR.socket.send(location.pathname);
     };
   },
 
   onMessage: function(evt) {
-      var obj = jQuery.parseJSON(evt.data);
-
-      if(obj['class'].match(/^notifications/)) {
-        WebSocketReceiver.processNotification(obj);
-      } else if (obj['class'] == 'people') {
-        WSR.debug("got a " + obj['class']);
-        WebSocketReceiver.processPerson(obj);
-
-      } else {
-        debug_string = "got a " + obj['class'];
-        if(obj.aspect_ids !== undefined){
-          debug_string +=  " for aspects " + obj.aspect_ids;
-        }
-
-        WSR.debug(debug_string);
-
-        if (obj['class']=="retractions") {
-          WebSocketReceiver.processRetraction(obj.post_guid);
-
-        } else if (obj['class']=="comments") {
-          WebSocketReceiver.processComment(obj.post_guid, obj.comment_guid, obj.html, {
-            'notification': obj.notification,
-            'mine?': obj['mine?'],
-            'my_post?': obj['my_post?']
-          });
-
-        } else if (obj['class']=="likes") {
-          WebSocketReceiver.processLike(obj.post_guid, obj.html);
-
-        } else {
-          WebSocketReceiver.processPost(obj.html, obj.aspect_ids);
-        }
-      }
-  },
-
-  processPerson: function(response) {
-    var form = $('.webfinger_form');
-    form.siblings('#loader').hide();
-    var result_ul = form.siblings('#request_result');
-    if(response.status == 'fail') {
-      result_ul.siblings('.error').show();
-      result_ul.find('.error').text(response.response).show();
-    } else {
-      stream = $('#people_stream');
-      stream.find('p').remove();
-      stream.prepend(response.html).slideDown('slow', function(){});
-      var first_li = result_ul.find('li:first');
-      first_li.hide();
-      first_li.after(response.html);
-      result_ul.find("[name='request[into]']").val(result_ul.attr('aspect_id'));
-      result_ul.children(':nth-child(2)').slideDown('fast', function(){});
-    }
-  },
+    var message = $.parseJSON(evt.data);
 
-
-  processNotification: function(notification){
-    Diaspora.page.notifications.showNotification(notification);
-  },
-
-  processRetraction: function(post_guid){
-    $("#" + post_guid).fadeOut(400, function() {
-      $(this).remove();
-    });
-    if($("#main_stream")[0].childElementCount === 0) {
-      $("#no_posts").fadeIn(200);
+    if(message["class"].match(/^notifications$/)) {
+      Diaspora.page.notifications.showNotification(message);
     }
-  },
-
-  processComment: function(postGUID, commentGUID, html, opts) {
-
-    if( $("#"+commentGUID).length === 0 ) {
-      var post = $("#"+postGUID),
-          prevComments = $('.comment.posted', post);
-
-      if(prevComments.length > 0) {
-        prevComments.last().after(
-          $(html).fadeIn("fast", function(){})
-        );
-      } else {
-        $('.comments', post).append(
-          $(html).fadeIn("fast", function(){})
-        );
-      }
-
-      var toggler = $('.toggle_post_comments', post).parent();
-
-      if(toggler.length > 0){
-        if( !$(".comments", post).is(':visible') ) {
-          toggler.click();
-        }
-
-        if( $(".show_comments", post).hasClass('hidden') ){
-          $(".show_comments", post).removeClass('hidden');
-        }
+    else {
+      switch(message["class"]) {
+        case "retractions":
+          ContentUpdater.removePostFromStream(message.post_guid);
+          break;
+        case "comments":
+          ContentUpdater.addCommentToPost(message.post_guid, message.comment_guid, message.html);
+          break;
+        case "likes":
+          ContentUpdater.addLikesToPost(message.post_guid, message.html);
+          break;
+        default:
+          if(WSR.onPageForAspects(message.aspects_ids)) {
+            ContentUpdater.addPostToStream(message.html);
+          }
+          break;
       }
     }
-
-    Diaspora.page.timeAgo.updateTimeAgo();
-    Diaspora.page.directionDetector.updateBinds();
-  },
-
-  processLike: function(targetGUID, html) {
-    $('.likes', "#" + targetGUID).first().html(html);
-  },
-
-  processPost: function(html, aspectIds) {
-    if(WebSocketReceiver.onpageForAspects(aspectIds)) {
-      ContentUpdater.addPostToStream(html);
-    }
-  },
-
-  onpageForClass: function(className) {
-    return (location.href.indexOf(className) != -1 );
   },
 
-  onpageForAspects: function(aspectIds) {
-    var streamIds = $('#main_stream').attr('data-guids'),
+  onPageForAspects: function(aspectIds) {
+    var streamIds = $("#main_stream").attr("data-guids"),
         found = false;
 
     $.each(aspectIds, function(index, value) {
@@ -149,20 +44,11 @@ var WebSocketReceiver = {
         return false;
       }
     });
+
     return found;
   },
 
   onStreamForAspect: function(aspectId, streamIds) {
     return (streamIds.search(aspectId) != -1);
-  },
-
-  onpageOne: function() {
-      var c = document.location.search.charAt(document.location.search.length-1);
-      return ((c === '') || (c === '1'));
-  },
-  debug: function(str) {
-    $("#debug").append("<p>" +  str);
   }
-};
-var WSR = WebSocketReceiver;
-
+};
\ No newline at end of file
diff --git a/public/stylesheets/sass/application.sass b/public/stylesheets/sass/application.sass
index e4d84ef015..6014e0d3a2 100644
--- a/public/stylesheets/sass/application.sass
+++ b/public/stylesheets/sass/application.sass
@@ -2361,10 +2361,6 @@ ul.show_comments,
     :color #eee
   :border 1px solid #ccc
 
-.webfinger_form
-  input[type='search']
-    :width 100%
-
 #sort_by
   :float right
   :color #777
diff --git a/spec/javascripts/content-updater-spec.js b/spec/javascripts/content-updater-spec.js
index 4325056a9c..fd548ad688 100644
--- a/spec/javascripts/content-updater-spec.js
+++ b/spec/javascripts/content-updater-spec.js
@@ -29,4 +29,67 @@ describe("ContentUpdater", function() {
       expect($("#no_posts").length).toEqual(0);
     });
   });
+
+  describe("removePostFromStream", function() {
+    var post, postGUID;
+    beforeEach(function() {
+      spec.loadFixture("aspects_index_with_posts");
+      post = $(".stream_element:first"),
+        postGUID = post.attr("id");
+
+      $.fx.off = true;
+    });
+
+    it("removes the post from the stream", function() {
+      expect($("#" + postGUID).length).toEqual(1);
+      ContentUpdater.removePostFromStream(postGUID);
+      expect($("#" + postGUID).length).toEqual(0);
+    });
+
+    it("shows the div that says you have no posts if there are no more post", function() {
+      $("#main_stream .stream_element").slice(1).remove();
+      expect($("#no_posts")).toHaveClass("hidden");
+      ContentUpdater.removePostFromStream(postGUID);
+      expect($("#no_posts")).not.toHaveClass("hidden");
+    });
+
+    afterEach(function() {
+      $.fx.off = false;
+    });
+  });
+
+  describe("addCommentToPost", function() {
+    var post, postGUID;
+    beforeEach(function() {
+      spec.loadFixture("aspects_index_with_posts");
+      post = $(".stream_element:first"),
+        postGUID = post.attr("id");
+    });
+
+    it("adds a comment to a post only if it doesn't already exist", function() {
+      var comments = post.find("ul.comments li");
+
+      expect(comments.length).toEqual(0);
+      ContentUpdater.addCommentToPost(postGUID, "YEAH", "<li id='YEAH'>Comment</li>");
+      expect(post.find("ul.comments li").length).toEqual(1);
+
+      ContentUpdater.addCommentToPost(postGUID, "YEAH", "<li id='YEAH'>Comment</li>");
+      expect(post.find("ul.comments li").length).toEqual(1);
+
+    });
+  });
+
+  describe("addLikesToPost", function() {
+    var post, postGUID;
+    beforeEach(function() {
+      spec.loadFixture("aspects_index_with_posts");
+      post = $(".stream_element:first"),
+        postGUID = post.attr("id");
+    });
+
+    it("adds the given html to a post's likes container", function() {
+      ContentUpdater.addLikesToPost(postGUID, "<p>1 like</p>");
+      expect(post.find(".likes .likes_container").html()).toEqual("<p>1 like</p>");
+    });
+  });
 });
-- 
GitLab