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) {
11 * Renders "new" comment indicators wherever necessary.
13 * @type {Drupal~behavior}
15 * @prop {Drupal~behaviorAttach} attach
16 * Attaches "new" comment indicators behavior.
18 Drupal.behaviors.commentNewIndicator = {
20 // Collect all "new" comment indicator placeholders (and their
21 // corresponding node IDs) newer than 30 days ago that have not already
22 // been read after their last comment timestamp.
24 const $placeholders = $(context)
25 .find('[data-comment-timestamp]')
28 const $placeholder = $(this);
29 const commentTimestamp = parseInt($placeholder.attr('data-comment-timestamp'), 10);
30 const nodeID = $placeholder.closest('[data-history-node-id]').attr('data-history-node-id');
31 if (Drupal.history.needsServerCheck(nodeID, commentTimestamp)) {
39 if ($placeholders.length === 0) {
43 // Fetch the node read timestamps from the server.
44 Drupal.history.fetchTimestamps(nodeIDs, () => {
45 processCommentNewIndicators($placeholders);
51 * Processes the markup for "new comment" indicators.
53 * @param {jQuery} $placeholders
54 * The elements that should be processed.
56 function processCommentNewIndicators($placeholders) {
57 let isFirstNewComment = true;
58 const newCommentString = Drupal.t('new');
61 $placeholders.each((index, placeholder) => {
62 $placeholder = $(placeholder);
63 const timestamp = parseInt($placeholder.attr('data-comment-timestamp'), 10);
64 const $node = $placeholder.closest('[data-history-node-id]');
65 const nodeID = $node.attr('data-history-node-id');
66 const lastViewTimestamp = Drupal.history.getLastRead(nodeID);
68 if (timestamp > lastViewTimestamp) {
69 // Turn the placeholder into an actual "new" indicator.
70 const $comment = $(placeholder)
71 .removeClass('hidden')
72 .text(newCommentString)
73 .closest('.js-comment')
74 // Add 'new' class to the comment, so it can be styled.
77 // Insert "new" anchor just before the "comment-<cid>" anchor if
78 // this is the first new comment in the DOM.
79 if (isFirstNewComment) {
80 isFirstNewComment = false;
81 $comment.prev().before('<a id="new" />');
82 // If the URL points to the first new comment, then scroll to that
84 if (window.location.hash === '#new') {
85 window.scrollTo(0, $comment.offset().top - Drupal.displace.offsets.top);
91 }(jQuery, Drupal, window));