2020-08-11 16:21:46 +08:00

74 lines
2.3 KiB
Plaintext

{%- if theme.firestore.enable %}
<script src="{{ theme.vendors.firebase_app }}"></script>
<script src="{{ theme.vendors.firebase_firestore }}"></script>
<script>
firebase.initializeApp({
apiKey : '{{ theme.firestore.apiKey }}',
projectId: '{{ theme.firestore.projectId }}'
});
function getCount(doc, increaseCount) {
// IncreaseCount will be false when not in article page
return doc.get().then(d => {
let count = 0;
if (!d.exists) { // Has no data, initialize count
if (increaseCount) {
doc.set({
count: 1
});
count = 1;
}
} else { // Has data
count = d.data().count;
if (increaseCount) {
// If first view this article
doc.set({ // Increase count
count: count + 1
});
count++;
}
}
return count;
});
}
function appendCountTo(el) {
return count => {
el.innerText = count;
}
}
</script>
<script{{ pjax }}>
(function() {
const db = firebase.firestore();
const articles = db.collection('{{ theme.firestore.collection }}');
if (CONFIG.page.isPost) { // Is article page
const title = document.querySelector('.post-title').innerText.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(appendCountTo(document.querySelector('.firestore-visitors-count')));
} else if (CONFIG.page.isHome) { // Is index page
const promises = [...document.querySelectorAll('.post-title')].map(element => {
const title = element.innerText.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) => {
appendCountTo(metas[idx])(val);
});
});
}
})();
</script>
{%- endif %}