-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
84 lines (65 loc) · 2.39 KB
/
app.js
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
const auth = firebase.auth();
const whenSignedIn = document.getElementById('whenSignedIn');
const whenSignedOut = document.getElementById('whenSignedOut');
const signInBtn = document.getElementById('signInBtn');
const signOutBtn = document.getElementById('signOutBtn');
const userPP = document.getElementById('profilePicture');
const provider = new firebase.auth.GoogleAuthProvider();
signInBtn.onclick = () => auth.signInWithPopup(provider);
signOutBtn.onclick = () => auth.signOut();
auth.onAuthStateChanged(user => {
if(user){
whenSignedIn.hidden = false;
whenSignedOut.hidden = true;
userPP.src = user.photoURL;
}else{
whenSignedIn.hidden = true;
whenSignedOut.hidden = false;
userPP.src = '#';
}
});
function slugify(text){
return text.toString().toLowerCase().trim()
.replace(/&/g,'-and-')
.replace(/[\s\W-]+/g,'-')
.replace(/[^a-zA-Z0-9-_]+/g,'')
}
db = firebase.firestore();
let ref;
let unsubscribe;
const postComment = document.getElementById('postComment');
const comments = document.getElementById('comments');
const commentInput = document.getElementById('commentInput');
auth.onAuthStateChanged(user => {
var postRef = db.collection(slugify(window.location.pathname));
if(user){
postComment.onclick = () => {
postRef.add({
uid: user.uid,
name: user.displayName,
comment: commentInput.value,
createdAt: Date.now()
});
commentInput.value = '';
commentInput.classList.add("is-valid");
commentInput.classList.remove("is-invalid");
}
}else{
postComment.onclick = () => {
commentInput.classList.add("is-invalid");
commentInput.classList.remove("is-valid");
alert("You must be signed in to comment")
}
}
unsubscribe = postRef
.orderBy('createdAt')
.onSnapshot(querySnapshot => {
const items = querySnapshot.docs.map(doc => {
let date = new Date(doc.data().createdAt);
return `<div>
<h6>${doc.data().name}</h6><div style="padding-left:2em;"><p>${doc.data().comment}</p><p style="font-size:0.5rem">${date.toUTCString()}</div>
</div>`
});
comments.innerHTML = items.reverse().join('');
});
});