summaryrefslogtreecommitdiff
path: root/layouts/_partials/scripts/action-menu-js.html
blob: df1c498c7a5482715a14c187853bc2448f237f03 (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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
{{ $pageId := . }}
<script defer>
/**
 * =================
 * Initialize all Action Menu features
 * - comment toggle
 * - comment count
 * - like
 * =================
 */

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

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

  if (!commentsToggle || !commentsSection) return;

  // click on toggle
  commentsToggle.addEventListener('click', function() {
    const isHidden = commentsSection.classList.contains('hidden');
    const entranceAnimation = 'animate-slide-in-down';
    const exitAnimation = 'animate-slide-out-up';

    if (isHidden) {
      // swtich on
      commentsSection.classList.remove('hidden', exitAnimation);
      commentsSection.classList.add(entranceAnimation);
    } else {
      // switch off
      commentsSection.classList.remove(entranceAnimation);
      commentsSection.classList.add(exitAnimation);
      setTimeout(() => {
        commentsSection.classList.add('hidden');
      }, 200);
    }
  });
}

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

function initializeCommentCount() {
  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 });
}

/**
 * =================
 * 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 setLikedState() {
    // update classes
    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');
    // update tooltip
    elements.btn.setAttribute('title',
      elements.container.classList.contains('liked')
        ? elements.btn.getAttribute('data-liked-title')
        : '为这篇文章献上心脏'
    );
  }

  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();
        updateOrganFarm(data.likes);
      }
    } catch(e) {
      console.log(e);
      elements.count.innerText = "❌";
    }
  }

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

    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;
      updateOrganFarm(data.likes);
      setLikedState();
    } catch(e) {
      console.log(e);
      alert("点赞失败,请稍后再试");
    }
  };

  function updateOrganFarm(count) {
    const organFarm = document.getElementById("organ-farm");
    const organCount = count || parseInt(elements.count.innerText);
    const organImages = [
      "https://image.guhub.cn/picgo2025/oragn-3.png",
      "https://image.guhub.cn/picgo2025/organ-1.png",
      "https://image.guhub.cn/picgo2025/organ-2.png"
    ];

    if (!organFarm) return;
    if (organFarm.classList.contains("hidden")) {
      organFarm.classList.remove("hidden");
      organFarm.classList.add("animate-slide-in-down");
    }

    organFarm.innerHTML = "";
    for (let i = 0; i < organCount; i++) {
      const img = document.createElement("img");
      img.className = "transition hover:scale-150 dark:invert";

      const sizeRange = [6, 10];
      const size = Math.floor(Math.random() * (sizeRange[1] - sizeRange[0] + 1)) + sizeRange[0];
      img.classList.add(`w-${size}`, `h-${size}`);

      img.src = organImages[Math.floor(Math.random() * organImages.length)];
      // randomly offset and rotate
      img.classList.add("rotate-" + Math.floor(Math.random() * 5));
      img.classList.add("translate-x-" + Math.floor(Math.random() * 5));
      img.classList.add("translate-y-" + Math.floor(Math.random() * 5));
      img.classList.add("opacity" + (100 - Math.floor(Math.random() * 3)*10));

      organFarm.appendChild(img);
    }
  }

  // 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
 * =================
 */

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

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

document.addEventListener('DOMContentLoaded', initializeFeatures);
</script>