comments.es6.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /**
  2. * @file
  3. * Customization of comments.
  4. */
  5. ((Drupal, once) => {
  6. /**
  7. * Initialize show/hide button for the comments.
  8. *
  9. * @param {Element} comments
  10. * The comment wrapper element.
  11. */
  12. function init(comments) {
  13. comments
  14. .querySelectorAll('[data-drupal-selector="comment"]')
  15. .forEach((comment) => {
  16. if (
  17. comment.nextElementSibling != null &&
  18. comment.nextElementSibling.matches('.indented')
  19. ) {
  20. comment.classList.add('has-children');
  21. }
  22. });
  23. comments.querySelectorAll('.indented').forEach((commentGroup) => {
  24. const showHideWrapper = document.createElement('div');
  25. showHideWrapper.setAttribute('class', 'show-hide-wrapper');
  26. const toggleCommentsBtn = document.createElement('button');
  27. toggleCommentsBtn.setAttribute('type', 'button');
  28. toggleCommentsBtn.setAttribute('aria-expanded', 'true');
  29. toggleCommentsBtn.setAttribute('class', 'show-hide-btn');
  30. toggleCommentsBtn.innerText = Drupal.t('Replies');
  31. commentGroup.parentNode.insertBefore(showHideWrapper, commentGroup);
  32. showHideWrapper.appendChild(toggleCommentsBtn);
  33. toggleCommentsBtn.addEventListener('click', (e) => {
  34. commentGroup.classList.toggle('hidden');
  35. e.currentTarget.setAttribute(
  36. 'aria-expanded',
  37. commentGroup.classList.contains('hidden') ? 'false' : 'true',
  38. );
  39. });
  40. });
  41. }
  42. /**
  43. * Attaches the comment behavior to comments.
  44. *
  45. * @type {Drupal~behavior}
  46. *
  47. * @prop {Drupal~behaviorAttach} attach
  48. * Attaches the show/hide behavior for indented comments.
  49. */
  50. Drupal.behaviors.comments = {
  51. attach(context) {
  52. once('comments', '[data-drupal-selector="comments"]', context).forEach(
  53. init,
  54. );
  55. },
  56. };
  57. })(Drupal, once);