3 * Attaches behaviors for the Comment module's "new" indicator.
5 * May only be loaded for authenticated users, with the History module
9 (function ($, Drupal, window) {
14 * Renders "new" comment indicators wherever necessary.
16 * @type {Drupal~behavior}
18 * @prop {Drupal~behaviorAttach} attach
19 * Attaches "new" comment indicators behavior.
21 Drupal.behaviors.commentNewIndicator = {
22 attach: function (context) {
23 // Collect all "new" comment indicator placeholders (and their
24 // corresponding node IDs) newer than 30 days ago that have not already
25 // been read after their last comment timestamp.
27 var $placeholders = $(context)
28 .find('[data-comment-timestamp]')
31 var $placeholder = $(this);
32 var commentTimestamp = parseInt($placeholder.attr('data-comment-timestamp'), 10);
33 var nodeID = $placeholder.closest('[data-history-node-id]').attr('data-history-node-id');
34 if (Drupal.history.needsServerCheck(nodeID, commentTimestamp)) {
43 if ($placeholders.length === 0) {
47 // Fetch the node read timestamps from the server.
48 Drupal.history.fetchTimestamps(nodeIDs, function () {
49 processCommentNewIndicators($placeholders);
55 * Processes the markup for "new comment" indicators.
57 * @param {jQuery} $placeholders
58 * The elements that should be processed.
60 function processCommentNewIndicators($placeholders) {
61 var isFirstNewComment = true;
62 var newCommentString = Drupal.t('new');
65 $placeholders.each(function (index, placeholder) {
66 $placeholder = $(placeholder);
67 var timestamp = parseInt($placeholder.attr('data-comment-timestamp'), 10);
68 var $node = $placeholder.closest('[data-history-node-id]');
69 var nodeID = $node.attr('data-history-node-id');
70 var lastViewTimestamp = Drupal.history.getLastRead(nodeID);
72 if (timestamp > lastViewTimestamp) {
73 // Turn the placeholder into an actual "new" indicator.
74 var $comment = $(placeholder)
75 .removeClass('hidden')
76 .text(newCommentString)
77 .closest('.js-comment')
78 // Add 'new' class to the comment, so it can be styled.
81 // Insert "new" anchor just before the "comment-<cid>" anchor if
82 // this is the first new comment in the DOM.
83 if (isFirstNewComment) {
84 isFirstNewComment = false;
85 $comment.prev().before('<a id="new" />');
86 // If the URL points to the first new comment, then scroll to that
88 if (window.location.hash === '#new') {
89 window.scrollTo(0, $comment.offset().top - Drupal.displace.offsets.top);
96 })(jQuery, Drupal, window);