summaryrefslogtreecommitdiff
path: root/layouts/_partials/scripts/action-menu-js.html
blob: e2db17e7e0463ca0fb8331b892a4d1df320a8e9a (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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
{{ $pageId := . }}
<script defer>
/**
 * =================
 * Initialize all Action Menu features
 * - comment toggle
 * - comment count
 * - like
 * =================
 */

function initializeFeatures() {
  const pageId = "{{ $pageId }}";
  if (!pageId) return;

  initializeComments();
  initializeLikes(pageId);
  initializeCommentCount();
}

/**
 * =================
 * Toggle Comment Section
 * =================
 */

function initializeComments() {
  const commentsToggle = document.getElementById('comments-toggle');
  const commentsSection = document.getElementById('comments-section');

  if (commentsToggle && commentsSection) {
    commentsToggle.addEventListener('click', function() {
      const isHidden = commentsSection.style.display === 'none';
      commentsSection.style.display = isHidden ? 'block' : 'none';
      this.style.background = isHidden ? 'rgba(0, 0, 0, 0.1)' : 'transparent';
    });
  }
}

/**
 * =================
 * Fetch and set Comment Count
 * =================
 */

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

  const observer = new MutationObserver(() => {
    const giscusIframe = document.querySelector('iframe.giscus-frame');
    if (giscusIframe) {
      giscusIframe.addEventListener('load', () => {
        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);
            commentCountEl.textContent = totalComments.toString();
          }
        });
      });
      observer.disconnect();
    }
  });

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

document.addEventListener('DOMContentLoaded', initializeCommentCount);

/**
 * =================
 * Initialize like functionality
 * =================
 */

function initializeLikes(pageId) {
  if (window.location.host !== 'www.geedea.pro') return;

  const elements = {
    count: document.getElementById("like-count-" + pageId),
    btn: document.getElementById("like-btn-" + pageId),
    container: document.getElementById("like-container-" + pageId),
    icon: document.getElementById("like-icon-" + pageId)
  };

  if (!elements.count || !elements.btn || !elements.container) return;

  function updateTooltip() {
    elements.btn.setAttribute('title',
      elements.container.classList.contains('liked')
        ? elements.btn.getAttribute('data-liked-title')
        : '为这篇文章献上心脏'
    );
  }

  function setLikedState() {
    elements.icon?.classList.add('liked-heart');
    elements.icon?.classList.add('animate-heart-beat');
    elements.count?.classList.add('liked-count');
    elements.btn.disabled = true;
    elements.container.classList.add('liked');
    updateTooltip();
  }

  async function fetchLikes() {
    try {
      const response = await fetch("https://like.guhub.cn/like/" + pageId);
      const data = await response.json();
      elements.count.innerText = data.likes ?? 0;
      if (localStorage.getItem("liked_" + pageId)) {
        setLikedState();
      }
    } catch(e) {
      console.log(e);
      elements.count.innerText = "❌";
    }
  }

  window.sendLike = async function(pageId) {
    if (localStorage.getItem("liked_" + pageId)) return;

    if (window.location.hostname !== 'localhost' && typeof umami !== 'undefined') {
      umami.track('👍 Hit Like Button');
    }

    try {
      const response = await fetch("https://like.guhub.cn/like/" + pageId, { method: "POST" });
      const data = await response.json();
      localStorage.setItem("liked_" + pageId, "1");
      elements.count.innerText = data.likes ?? 1;
      setLikedState();
    } catch(e) {
      console.log(e);
      alert("点赞失败,请稍后再试");
    }
  };

  // fetch likes when action menu is visible
  const observer = new IntersectionObserver((entries, obs) => {
    if (entries[0].isIntersecting) {
      fetchLikes();
      obs.disconnect();
    }
  });
  observer.observe(document.getElementById("action-menu"));
}

/**
 * =================
 * Load features after DOMContentLoaded
 * =================
 */

document.addEventListener('DOMContentLoaded', () => {
  if ('requestIdleCallback' in window) {
    requestIdleCallback(initializeFeatures);
  } else {
    setTimeout(initializeFeatures, 300);
  }
});
</script>