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 * Processes the markup for "new comment" indicators.
13 * @param {jQuery} $placeholders
14 * The elements that should be processed.
16 function processCommentNewIndicators($placeholders) {
17 let isFirstNewComment = true;
18 const newCommentString = Drupal.t('new');
21 $placeholders.each((index, placeholder) => {
22 $placeholder = $(placeholder);
23 const timestamp = parseInt(
24 $placeholder.attr('data-comment-timestamp'),
27 const $node = $placeholder.closest('[data-history-node-id]');
28 const nodeID = $node.attr('data-history-node-id');
29 const lastViewTimestamp = Drupal.history.getLastRead(nodeID);
31 if (timestamp > lastViewTimestamp) {
32 // Turn the placeholder into an actual "new" indicator.
33 const $comment = $(placeholder)
34 .removeClass('hidden')
35 .text(newCommentString)
36 .closest('.js-comment')
37 // Add 'new' class to the comment, so it can be styled.
40 // Insert "new" anchor just before the "comment-<cid>" anchor if
41 // this is the first new comment in the DOM.
42 if (isFirstNewComment) {
43 isFirstNewComment = false;
44 $comment.prev().before('<a id="new" />');
45 // If the URL points to the first new comment, then scroll to that
47 if (window.location.hash === '#new') {
50 $comment.offset().top - Drupal.displace.offsets.top,
59 * Renders "new" comment indicators wherever necessary.
61 * @type {Drupal~behavior}
63 * @prop {Drupal~behaviorAttach} attach
64 * Attaches "new" comment indicators behavior.
66 Drupal.behaviors.commentNewIndicator = {
68 // Collect all "new" comment indicator placeholders (and their
69 // corresponding node IDs) newer than 30 days ago that have not already
70 // been read after their last comment timestamp.
72 const $placeholders = $(context)
73 .find('[data-comment-timestamp]')
76 const $placeholder = $(this);
77 const commentTimestamp = parseInt(
78 $placeholder.attr('data-comment-timestamp'),
81 const nodeID = $placeholder
82 .closest('[data-history-node-id]')
83 .attr('data-history-node-id');
84 if (Drupal.history.needsServerCheck(nodeID, commentTimestamp)) {
92 if ($placeholders.length === 0) {
96 // Fetch the node read timestamps from the server.
97 Drupal.history.fetchTimestamps(nodeIDs, () => {
98 processCommentNewIndicators($placeholders);
102 })(jQuery, Drupal, window);