summaryrefslogtreecommitdiff
path: root/layouts/_partials/posts/action-menu/comment-button.html
blob: 7dcea107e058f38d4e9132f17528a989dd4f066a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
{{ partial "components/toggle-button.html" (dict 
  "id" "comments"
  "title" (T "actionMenu.comment")
  "icon" "/img/comments.svg"
  "countId" "comment-count" 
  "group" "action-menu-section"
) }}

<script>
// initialize button features and comment count
document.addEventListener('DOMContentLoaded', () => {

  function initCommentCount() {
    const commentCountEl = document.getElementById('comment-count');
    if (!commentCountEl) return;

    const observer = new MutationObserver(() => {
      // check if giscus is loaded
      const giscusIframe = document.querySelector('iframe.giscus-frame');
      if (!giscusIframe) return;

      giscusIframe.addEventListener('load', () => {
        // receive message from giscus iframe
        window.addEventListener('message', function(event) {
          if (event.origin !== 'https://giscus.app') return;
          const giscusData = event.data;
          if (giscusData.giscus?.discussion) {
            const discussion = giscusData.giscus.discussion;
            const totalComments = (discussion.totalCommentCount || 0) + (discussion.totalReplyCount || 0);
            // set comment count
            commentCountEl.textContent = totalComments.toString();
          // if no discussion found, set to 0
          } else commentCountEl.textContent = '0';
        });
      });

      observer.disconnect();
    });
    observer.observe(document.body, { childList: true, subtree: true });
  }

  initCommentCount();
});
</script>