JO
2024-08-13 bf781fe79d3f2babeeaa9dd55e5f4a5da04e9977
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
/* global CONFIG, firebase */
 
firebase.initializeApp({
  apiKey   : CONFIG.firestore.apiKey,
  projectId: CONFIG.firestore.projectId
});
 
(function() {
  const getCount = (doc, increaseCount) => {
    // IncreaseCount will be false when not in article page
    return doc.get().then(d => {
      // Has no data, initialize count
      let count = d.exists ? d.data().count : 0;
      // If first view this article
      if (increaseCount) {
        // Increase count
        count++;
        doc.set({
          count
        });
      }
      return count;
    });
  };
 
  const db = firebase.firestore();
  const articles = db.collection(CONFIG.firestore.collection);
 
  document.addEventListener('page:loaded', () => {
 
    if (CONFIG.page.isPost) {
      // Fix issue #118
      // https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
      const title = document.querySelector('.post-title').textContent.trim();
      const doc = articles.doc(title);
      let increaseCount = CONFIG.hostname === location.hostname;
      if (localStorage.getItem(title)) {
        increaseCount = false;
      } else {
        // Mark as visited
        localStorage.setItem(title, true);
      }
      getCount(doc, increaseCount).then(count => {
        document.querySelector('.firestore-visitors-count').innerText = count;
      });
    } else if (CONFIG.page.isHome) {
      const promises = [...document.querySelectorAll('.post-title')].map(element => {
        const title = element.textContent.trim();
        const doc = articles.doc(title);
        return getCount(doc);
      });
      Promise.all(promises).then(counts => {
        const metas = document.querySelectorAll('.firestore-visitors-count');
        counts.forEach((val, idx) => {
          metas[idx].innerText = val;
        });
      });
    }
  });
})();