Browse Source

Heartbeat comments and Like now working on Block

logicp 7 years ago
parent
commit
7a5bd38161

+ 1 - 0
config/install/heartbeat.heartbeatcomment.yml

@@ -0,0 +1 @@
+heartbeat:

+ 8 - 0
config/schema/heartbeat.schema.yml

@@ -100,3 +100,11 @@ heartbeat_hashtag.config:
     tid:
       type: integer
       label: 'The Taxonomy term to be used when filtering a Heartbeat Stream'
+
+heartbeat_comment.config:
+  type: config_object
+  label: 'Comment configuration'
+  mapping:
+    entity_id:
+      type: integer
+      label: 'The ID of the entity being commented on'

+ 9 - 0
css/heartbeat.css

@@ -122,3 +122,12 @@ Temporarily hiding all irrelevant content */
 /*@media all and (min-width: 300px) {*/
 /*}*/
 
+
+
+/*TODO
+
+  //add responsiveness for colorbox on mobile using something like the following:
+
+    max-width: 400px;
+height: auto!important;
+*/

+ 3 - 3
heartbeat.page.inc

@@ -23,7 +23,7 @@ function template_preprocess_heartbeat(array &$variables) {
   // Fetch Heartbeat Entity Object.
   $entity = $variables['elements']['#heartbeat'];
 
-  if ($entity->isPublished()) {
+  if ($entity->getEntityType() == 'heartbeat' && $entity->isPublished()) {
     $node = \Drupal::entityTypeManager()
       ->getStorage('node')
       ->load($entity->getNid()->getValue()[0]['target_id']);
@@ -32,10 +32,10 @@ function template_preprocess_heartbeat(array &$variables) {
       $renderedNode = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'full');
       $variables['content']['node'] = $renderedNode;
     }
-
+  }
     // Helpful $content variable for templates.
     foreach (Element::children($variables['elements']) as $key) {
       $variables['content'][$key] = $variables['elements'][$key];
     }
-  }
+
 }

+ 7 - 0
heartbeat.routing.yml

@@ -120,3 +120,10 @@ heartbeat.heartbeat_filter_feed:
   requirements:
     _access: 'TRUE'
 
+heartbeat.heartbeat_comment_update:
+  path: '/heartbeat/commentupdate/{entity_id}'
+  defaults:
+    _controller: '\Drupal\heartbeat\Controller\HeartbeatController::commentConfigUpdate'
+    _title: 'Heartbeat Comment Config Update'
+  requirements:
+    _access: 'TRUE'

+ 40 - 2
js/heartbeat.js

@@ -74,9 +74,10 @@
                   }
                 });
               }
-            }
+            };
 
             listenImages();
+            listenCommentPost();
         }
     };
 
@@ -94,10 +95,47 @@
   }
 
   function listenImages() {
+    let cboxOptions = {
+      width: '95%',
+      height: '95%',
+      maxWidth: '960px',
+      maxHeight: '960px',
+    };
+
     $('.heartbeat-content').find('img').each(function() {
-      $(this).colorbox({href: $(this).attr('src')});
+      $(this).colorbox({href: $(this).attr('src'), cboxOptions});
     });
   }
 
+  function listenCommentPost() {
+    let comments = document.querySelectorAll('[data-drupal-selector]');
+
+    for (let i = 0; i < comments.length; i++) {
+      let comment = comments[i];
+      console.dir(comment);
+      comment.addEventListener('click', function() {
+        getParent(comment);
+      })
+    }
+  }
+
+  function getParent(node) {
+    console.dir(node);
+    if (node.classList.contains('heartbeat-comment')) {
+      let id = node.id.substr(node.id.indexOf('-')+1);
+      $.ajax({
+        type: 'POST',
+        url:'/heartbeat/commentupdate/' + id,
+        success: function(response) {
+
+          console.log(response);
+        }
+      });
+    } else {
+      getParent(node.parentNode);
+    }
+  }
+
+
 })(jQuery, Drupal, drupalSettings);
 

+ 28 - 0
src/Ajax/ClearPreviewCommand.php

@@ -0,0 +1,28 @@
+<?php
+
+namespace Drupal\heartbeat\Ajax;
+
+/**
+ * Created by IntelliJ IDEA.
+ * User: logicp
+ * Date: 5/28/17
+ * Time: 11:38 PM
+ */
+
+use Drupal\Core\Ajax\CommandInterface;
+
+class ClearPreviewCommand implements CommandInterface {
+    protected $message;
+
+    public function __construct($message) {
+        $this->message = $message;
+    }
+
+    public function render() {
+
+        return array(
+            'command' => 'clearPreview',
+            'clear' => $this->message,
+        );
+    }
+}

+ 8 - 1
src/Controller/HeartbeatController.php

@@ -168,7 +168,7 @@ class HeartbeatController extends ControllerBase implements ContainerInjectionIn
     $myConfig->set('message', $arg)->save();
     \Drupal::logger('HeartbeatController')->debug('My argument is %arg', ['%arg' => $arg]);
 
-    return BlockViewBuilder::lazyBuilder('heartbeatblock', 'teaser');
+    return BlockViewBuilder::lazyBuilder('heartbeatblock', 'full');
   }
 
 
@@ -184,4 +184,11 @@ class HeartbeatController extends ControllerBase implements ContainerInjectionIn
 
   }
 
+  public function commentConfigUpdate($entity_id) {
+    $commentConfig = \Drupal::configFactory()->getEditable('heartbeat_comment.settings');
+    $commentConfig->set('entity_id', $entity_id)->save();
+
+    return true;
+  }
+
 }

+ 81 - 0
src/Form/HeartbeatCommentForm.php

@@ -0,0 +1,81 @@
+<?php
+
+namespace Drupal\heartbeat\Form;
+
+use Drupal\Core\Form\FormBase;
+use Drupal\Core\Form\FormStateInterface;
+use Drupal\Comment\Entity\Comment;
+
+/**
+ * Class HeartbeatCommentForm.
+ *
+ * @property  entity
+ * @package Drupal\heartbeat\Form
+ */
+class HeartbeatCommentForm extends FormBase {
+  protected $entityId;
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getFormId() {
+    return 'heartbeat_comment_form';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function buildForm(array $form, FormStateInterface $form_state) {
+    $form['comment_body'] = array(
+      '#type' => 'textarea',
+      '#title' => $this->t('Comment Body'),
+    );
+
+    $form['post'] = array(
+      '#type' => 'submit',
+      '#description' => 'Comment',
+      '#value' => t('Comment'),
+      '#ajax' => [
+        'callback' => '::commentAjaxSubmit',
+        'progress' => array(
+          'type' => 'throbber',
+          'message' => t('Posting Comment'),
+        ),
+      ]
+    );
+
+    return $form;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function commentAjaxSubmit(array &$form, FormStateInterface $form_state) {
+
+    $commentBody = $form_state->getValue('comment_body');
+    $config = \Drupal::config('heartbeat_comment.settings');
+
+
+    $comment = Comment::create([
+      'entity_type' => 'heartbeat',
+      'entity_id' => $config->get('entity_id'),
+      'field_name' => 'comment',
+      'comment_body' => $commentBody,
+      'comment_type' => 'comment',
+      'subject' => 'Heartbeat Comment',
+    ]);
+
+    if ($comment->save()) {
+      return true;
+    }
+
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function submitForm(array &$form, FormStateInterface $form_state) {
+
+  }
+
+}

+ 52 - 15
src/Plugin/Block/HeartbeatBlock.php

@@ -3,9 +3,11 @@
 namespace Drupal\heartbeat\Plugin\Block;
 
 use Drupal\Core\Block\BlockBase;
+use Drupal\Core\Config\ConfigFactory;
 use Drupal\Core\Entity\EntityTypeManager;
 use Drupal\Core\Form\FormBuilder;
 use Drupal\flag\FlagService;
+use Drupal\comment\Entity\Comment;
 use Drupal\User\Entity\User;
 use Drupal\Flag\Entity\Flag;
 use Drupal\Core\Datetime\DateFormatter;
@@ -16,6 +18,7 @@ use Drupal\Core\Database\Database;
 use Drupal\heartbeat\HeartbeatTypeServices;
 use Drupal\heartbeat\HeartbeatStreamServices;
 use Drupal\heartbeat\HeartbeatService;
+use Drupal\heartbeat\Plugin\Block\HeartbeatCommentBlock;
 
 //*  deriver = "Drupal\heartbeat\Plugin\Derivative\HeartbeatBlockDeriver
 
@@ -55,6 +58,9 @@ class HeartbeatBlock extends BlockBase implements ContainerFactoryPluginInterfac
   protected $flagService;
 
   protected $formBuilder;
+
+  protected $configFactory;
+
   /**
    * Construct.
    *
@@ -71,7 +77,7 @@ class HeartbeatBlock extends BlockBase implements ContainerFactoryPluginInterfac
         $plugin_definition,
         HeartbeatTypeServices $heartbeat_heartbeattype,
 	HeartbeatStreamServices $heartbeatstream,
-	HeartbeatService $heartbeat, EntityTypeManager $entity_type_manager, DateFormatter $date_formatter, FlagService $flag_service, FormBuilder $form_builder
+	HeartbeatService $heartbeat, EntityTypeManager $entity_type_manager, DateFormatter $date_formatter, FlagService $flag_service, FormBuilder $form_builder, ConfigFactory $configFactory
   ) {
     parent::__construct($configuration, $plugin_id, $plugin_definition);
     $this->heartbeatTypeServices = $heartbeat_heartbeattype;
@@ -81,6 +87,7 @@ class HeartbeatBlock extends BlockBase implements ContainerFactoryPluginInterfac
     $this->dateFormatter = $date_formatter;
     $this->flagService = $flag_service;
     $this->formBuilder = $form_builder;
+    $this->configFactory = $configFactory;
   }
   /**
    * {@inheritdoc}
@@ -96,7 +103,8 @@ class HeartbeatBlock extends BlockBase implements ContainerFactoryPluginInterfac
       $container->get('entity_type.manager'),
       $container->get('date.formatter'),
       $container->get('flag'),
-      $container->get('form_builder')
+      $container->get('form_builder'),
+      $container->get('config.factory')
     );
   }
 
@@ -175,40 +183,69 @@ class HeartbeatBlock extends BlockBase implements ContainerFactoryPluginInterfac
         $profilePic = $user->get('user_picture')->getValue()[0]['target_id'];
       }
 
-//      $commentForm = $this->formBuilder->getForm('Drupal\comment\CommentForm', $heartbeat);
-
-//      $flagRenderable = $flagLink->toRenderable();
-
-      if (null === $profilePic) {
+      if (NULL === $profilePic) {
         $profilePic = 86;
       }
 
       $pic = File::load($profilePic);
 
-      if ($pic !== null) {
-        $style = $this->entityTypeManager->getStorage('image_style')->load('thumbnail');
-
+      if ($pic !== NULL) {
+        $style = $this->entityTypeManager->getStorage('image_style')
+          ->load('thumbnail');
         $rendered = $style->buildUrl($pic->getFileUri());
       }
 
+      $cids = \Drupal::entityQuery('comment')
+        ->condition('entity_id', $heartbeat->id())
+        ->condition('entity_type', 'heartbeat')
+        ->sort('cid', 'DESC')
+        ->execute();
+
+      $comments = [];
 
-//TODO GET ACTION AND APPEND TO CLASSES IN FLAG WRAPPER
+      foreach($cids as $cid) {
 
+//        $comment = $this->entityTypeManager->getStorage('comment')->load($cid);
+          $comment = Comment::load($cid);
+//        $comment->delete();
 
+        $comments[] = $comment->get('comment_body')->value;
+      }
+
+//      $heartbeatCommentBlock = \Drupal\block\Entity\Block::load('heartbeatcommentblock');
+//      $commentForm = $this->entityTypeManager->getViewBuilder('block')
+//        ->view($heartbeatCommentBlock);
 
+      $form = \Drupal::service('form_builder')->getForm('\Drupal\heartbeat\Form\HeartbeatCommentForm', $heartbeat);
 
+      $likeFlag = $this->flagService->getFlagById('heartbeat_like');
 
+      $flagKey = 'flag_' . $likeFlag->id();
+      $flagData = [
+        '#lazy_builder' => ['flag.link_builder:build', [
+          $heartbeat->getEntityTypeId(),
+          $heartbeat->id(),
+          $likeFlag->id(),
+        ]],
+        '#create_placeholder' => TRUE,
+      ];
 
       $messages[] = array('heartbeat' => $heartbeat->getMessage()->getValue()[0]['value'],
         'userPicture' => $rendered,
         'userId' => $user->id(),
         'timeAgo' => $timeago,
         'id' => $heartbeat->id(),
-//        'friendFlag' => $flagUrl,
-//        'friendFlagText' => $flagText,
-//        'flagId' => $flag->id(),
         'user' => $userView,
-//        'commentForm' => $commentForm
+        'commentForm' => $form,
+        'comments' => $comments,
+        'likeFlag' => [$flagKey => $flagData],
         );
     }
 }
+
+
+/******************************
+ * *****FOR COMMENT FEED*******
+ * *****ON EACH HEARTBEAT******
+ * ****************************/
+

+ 78 - 0
src/Plugin/Block/HeartbeatCommentBlock.php

@@ -0,0 +1,78 @@
+<?php
+
+namespace Drupal\heartbeat\Plugin\Block;
+
+use Drupal\Core\Block\BlockBase;
+use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
+use Drupal\heartbeat\Form\HeartbeatCommentForm;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Drupal\Core\Form\FormBuilder;
+
+/**
+ * Provides a 'HeartbeatCommentBlock' block.
+ *
+ * @Block(
+ *  id = "heartbeat_comment_block",
+ *  admin_label = @Translation("Heartbeat comment block"),
+ * )
+ */
+class HeartbeatCommentBlock extends BlockBase implements ContainerFactoryPluginInterface {
+
+  /**
+   * Drupal\Core\Form\FormBuilder definition.
+   *
+   * @var Drupal\Core\Form\FormBuilder
+   */
+  protected $form_builder;
+  protected $entityId;
+
+  /**
+   * Construct.
+   *
+   * @param array $configuration
+   *   A configuration array containing information about the plugin instance.
+   * @param string $plugin_id
+   *   The plugin_id for the plugin instance.
+   * @param string $plugin_definition
+   *   The plugin implementation definition.
+   */
+  public function __construct(
+        array $configuration,
+        $plugin_id,
+        $plugin_definition,
+        FormBuilder $form_builder
+  ) {
+    parent::__construct($configuration, $plugin_id, $plugin_definition);
+    $this->form_builder = $form_builder;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
+    return new static(
+      $configuration,
+      $plugin_id,
+      $plugin_definition,
+      $container->get('form_builder')
+    );
+  }
+
+
+
+  /**
+   * {@inheritdoc}
+   */
+  public function build() {
+    $form = $this->form_builder->getForm('\Drupal\heartbeat\Form\HeartbeatCommentForm');
+    if ($form instanceof HeartbeatCommentForm) {
+      $form->setEntityId($this->entityId);
+    }
+    return $form;
+  }
+
+  public function setEntityId($id) {
+    $this->entityId = $id;
+  }
+
+}

+ 58 - 27
src/Plugin/Block/HeartbeatHashBlock.php

@@ -2,6 +2,7 @@
 
 namespace Drupal\heartbeat\Plugin\Block;
 
+use Drupal\comment\Entity\Comment;
 use Drupal\Core\Block\BlockBase;
 use Drupal\Core\Entity\EntityTypeManager;
 use Drupal\Core\Form\FormBuilder;
@@ -162,47 +163,77 @@ class HeartbeatHashBlock extends BlockBase implements ContainerFactoryPluginInte
 
     }
 
-    private function renderMessage(array &$messages, $heartbeat) {
+  private function renderMessage(array &$messages, $heartbeat) {
 
-      $timeago = $this->dateFormatter->formatInterval(REQUEST_TIME - $heartbeat->getCreatedTime());
-      $user = $heartbeat->getOwner();
+    $timeago = $this->dateFormatter->formatInterval(REQUEST_TIME - $heartbeat->getCreatedTime());
+    $user = $heartbeat->getOwner();
 //      $rendered = $this->entityTypeManager->getViewBuilder('user')->view($user, 'full');
-      $userView = user_view($user, 'compact');
+    $userView = user_view($user, 'compact');
 //      $flag = $this->flagService->getFlagById("friendship");
 //      $flagLink = $flag->getLinkTypePlugin()->getAsLink($flag, $user);
 //      $flagUrl = $flagLink->getUrl()->toString();
 //      $flagText = $flagLink->getText();
+    $userPic = $user->get('user_picture')->getValue();
+    if (!empty($userPic)) {
       $profilePic = $user->get('user_picture')->getValue()[0]['target_id'];
+    }
 
-//      $commentForm = $this->formBuilder->getForm('Drupal\comment\CommentForm', $heartbeat);
+    if (NULL === $profilePic) {
+      $profilePic = 86;
+    }
 
-//      $flagRenderable = $flagLink->toRenderable();
+    $pic = File::load($profilePic);
 
-      if ($profilePic === null) {
-        $profilePic = 86;
-      }
+    if ($pic !== NULL) {
+      $style = $this->entityTypeManager->getStorage('image_style')
+        ->load('thumbnail');
+      $rendered = $style->buildUrl($pic->getFileUri());
+    }
 
-      $pic = File::load($profilePic);
+    $cids = \Drupal::entityQuery('comment')
+      ->condition('entity_id', $heartbeat->id())
+      ->condition('entity_type', 'heartbeat')
+      ->sort('cid', 'DESC')
+      ->execute();
 
-      if ($pic !== null) {
-        $style = $this->entityTypeManager->getStorage('image_style')->load('thumbnail');
+    $comments = [];
 
-        $rendered = $style->buildUrl($pic->getFileUri());
-      }
+    foreach($cids as $cid) {
 
+//        $comment = $this->entityTypeManager->getStorage('comment')->load($cid);
+      $comment = Comment::load($cid);
+//        $comment->delete();
 
-//TODO GET ACTION AND APPEND TO CLASSES IN FLAG WRAPPER
-
-      $messages[] = array('heartbeat' => $heartbeat->getMessage()->getValue()[0]['value'],
-        'userPicture' => $rendered,
-        'userId' => $user->id(),
-        'timeAgo' => $timeago,
-        'id' => $heartbeat->id(),
-//        'friendFlag' => $flagUrl,
-//        'friendFlagText' => $flagText,
-//        'flagId' => $flag->id(),
-        'user' => $userView,
-//        'commentForm' => $commentForm
-        );
+      $comments[] = $comment->get('comment_body')->value;
     }
+
+//      $heartbeatCommentBlock = \Drupal\block\Entity\Block::load('heartbeatcommentblock');
+//      $commentForm = $this->entityTypeManager->getViewBuilder('block')
+//        ->view($heartbeatCommentBlock);
+
+    $form = \Drupal::service('form_builder')->getForm('\Drupal\heartbeat\Form\HeartbeatCommentForm', $heartbeat);
+
+    $likeFlag = $this->flagService->getFlagById('heartbeat_like');
+
+    $flagKey = 'flag_' . $likeFlag->id();
+    $flagData = [
+      '#lazy_builder' => ['flag.link_builder:build', [
+        $heartbeat->getEntityTypeId(),
+        $heartbeat->id(),
+        $likeFlag->id(),
+      ]],
+      '#create_placeholder' => TRUE,
+    ];
+
+    $messages[] = array('heartbeat' => $heartbeat->getMessage()->getValue()[0]['value'],
+      'userPicture' => $rendered,
+      'userId' => $user->id(),
+      'timeAgo' => $timeago,
+      'id' => $heartbeat->id(),
+      'user' => $userView,
+      'commentForm' => $form,
+      'comments' => $comments,
+      'likeFlag' => [$flagKey => $flagData],
+    );
+  }
 }

+ 22 - 9
templates/heartbeat-stream.html.twig

@@ -22,16 +22,29 @@
   {% autoescape false %}
   {% for message in messages %}
     <div{{ attributes.addClass('heartbeat-message') }} id="heartbeat-{{ message.id }}">
-      <div class="heartbeat-owner">
-        <a href="/user/{{ message.userId }}"><img src="{{ message.userPicture }}" /></a>
-        {{ message.user }}
-        <div class="time-ago">{{ message.timeAgo }} ago</div>
+      {#{{ message }}#}
+      <div class="heartbeat-message-wrap">
+        <div class="heartbeat-owner">
+          <a href="/user/{{ message.userId }}"><img src="{{ message.userPicture }}" /></a>
+          {{ message.user }}
+          <div class="time-ago">{{ message.timeAgo }} ago</div>
+        </div>
+        <div class="heartbeat-content">
+        {{ message.heartbeat }}
+        </div>
       </div>
-      <div class="heartbeat-content">
-      {{ message.heartbeat }}
-      </div>
-      <div class="heartbeat-comment">
-        {{ message.commentForm }}
+      <div class="heartbeat-interaction-wrap">
+        <div class="heartbeat-like">
+          {{ message.likeFlag }}
+        </div>
+        <div class="heartbeat-comment" id="comment-{{ message.id }}">
+          {{ message.commentForm }}
+          <div class="heartbeat-comments">
+            {% for comment in message.comments %}
+            {{ comment }}
+            {% endfor %}
+          </div>
+        </div>
       </div>
     </div>
   {% endfor %}

+ 3 - 2
templates/heartbeat.html.twig

@@ -17,7 +17,8 @@
 #}
 <div{{ attributes.addClass('heartbeat') }}>
   {% if content %}
-    {{- content.message -}}
-    {{- content.node -}}
+    {{- content -}}
+    {#{{- content.message -}}#}
+    {#{{- content.node -}}#}
   {% endif %}
 </div>