-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
222 lines (194 loc) · 5.95 KB
/
index.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
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
// Import stylesheets
import './style.css';
// Firebase App (the core Firebase SDK) is always required
import { initializeApp } from 'firebase/app';
// Add the Firebase products and methods that you want to use
import { getAuth,
EmailAuthProvider,
signOut,
onAuthStateChanged
} from 'firebase/auth';
import {
getFirestore,
addDoc,
collection,
query,
orderBy,
onSnapshot,
doc,
setDoc,
where
} from 'firebase/firestore';
import * as firebaseui from 'firebaseui';
// Document elements
const startRsvpButton = document.getElementById('startRsvp');
const guestbookContainer = document.getElementById('guestbook-container');
const form = document.getElementById('leave-message');
const input = document.getElementById('message');
const guestbook = document.getElementById('guestbook');
const numberAttending = document.getElementById('number-attending');
const rsvpYes = document.getElementById('rsvp-yes');
const rsvpNo = document.getElementById('rsvp-no');
let rsvpListener = null;
let guestbookListener = null;
let db, auth;
async function main() {
// Add Firebase project configuration object here
const firebaseConfig = {
apiKey: "AIzaSyD3TDZAGMd7IlArnGpHApfFHflqQzfY81w",
authDomain: "fir-web-codelab-65364.firebaseapp.com",
projectId: "fir-web-codelab-65364",
storageBucket: "fir-web-codelab-65364.appspot.com",
messagingSenderId: "686471591694",
appId: "1:686471591694:web:2467a9c3bfbdbfa342495f"
};
// Initializa Firebase
initializeApp(firebaseConfig);
auth = getAuth();
db = getFirestore();
// FirebaseUI config
const uiConfig = {
credentialHelper: firebaseui.auth.CredentialHelper.NONE,
signInOptions: [
// Email / Password Provider.
EmailAuthProvider.PROVIDER_ID,
],
callbacks: {
signInSuccessWithAuthResult: function (authResult, redirectUrl) {
// Handle sign-in.
// Return false to avoid redirect.
return false;
},
},
};
// const ui = new firebaseui.auth.AuthUI(auth);
// Initialize the FirebaseUI widget using Firebase
const ui = new firebaseui.auth.AuthUI(auth);
startRsvpButton.addEventListener('click', () => {
if (auth.currentUser) {
// User is signed in; allows user to sign out
signOut(auth);
} else {
// No user is signed in; allows user to sign in
ui.start('#firebaseui-auth-container', uiConfig);
}
});
// Listen to the current Auth state
onAuthStateChanged(auth, user => {
if (user) {
startRsvpButton.textContent = 'LOGOUT';
// Show guestbook to logged-in users
guestbookContainer.style.display = 'block';
// Subscribe to the guestbook collection
subscribeGuestbook();
// Subscribe to the user's RSVP
subscribeCurrentRSVP(user);
} else {
startRsvpButton.textContent = 'RSPV';
// Hide guestbook for non-logged-in users
guestbookContainer.style.display = 'none';
// Unsubscribe from the guestbook collection
unsubscribeGuestbook();
// Unsubscribe from the guestbook collection
unsubscribeCurrentRSVP();
}
});
// Listen to the form submission
form.addEventListener('submit', async e => {
// Prevent the default form redirect
e.preventDefault();
// Write a new message to the database collection "guestbook"
addDoc(collection(db, 'guestbook'), {
text: input.value,
timestamp: Date.now(),
name: auth.currentUser.displayName,
userId: auth.currentUser.uid
});
// clear message input field
input.value = '';
// Return false to avoid redirect
return false;
});
// Listen to RSVP responses
rsvpYes.onclick = async () => {
// Get a reference to the user's document in the attendees collection
const userRef = doc(db, 'attendees', auth.currentUser.uid);
// If they RSVP'd yes, save a document with attendi()ng: true
try {
await setDoc(userRef, {
attending: true
});
} catch (e) {
console.error(e);
}
};
rsvpNo.onclick = async () => {
// Get a reference to the user's document in the attendees collection
const userRef = doc(db, 'attendees', auth.currentUser.uid);
// If they RSVP'd yes, save a document with attending: true
try {
await setDoc(userRef, {
attending: false
});
} catch (e) {
console.error(e);
}
};
// Listen for attendee list
const attendingQuery = query(
collection(db, 'attendees'),
where('attending', '==', true)
);
const unsubscribe = onSnapshot(attendingQuery, snap => {
const newAttendeeCount = snap.docs.length;
numberAttending.innerHTML = newAttendeeCount + ' people going';
});
}
main();
// Listen to guestbook updates
function subscribeGuestbook() {
const q = query(collection(db, 'guestbook'), orderBy('timestamp', 'desc'));
guestbookListener = onSnapshot(q, snaps => {
// Reset page
guestbook.innerHTML = '';
// Loop through documents in database
snaps.forEach(doc => {
// Create an HTML entry for each document and add it to the chat
const entry = document.createElement('p');
entry.textContent = doc.data().name + ': ' + doc.data().text;
guestbook.appendChild(entry);
});
});
}
// Unsubscribe from guestbook updates
function unsubscribeGuestbook() {
if (guestbookListener != null) {
guestbookListener();
guestbookListener = null;
}
}
// Listen for attendee list
function subscribeCurrentRSVP(user) {
const ref = doc(db, 'attendees', user.uid);
rsvpListener = onSnapshot(ref, doc => {
if (doc && doc.data()) {
const attendingResponse = doc.data().attending;
// Update css classes for buttons
if (attendingResponse) {
rsvpYes.className = 'clicked';
rsvpNo.className = '';
} else {
rsvpYes.className = '';
rsvpNo.className = 'clicked';
}
}
});
}
function unsubscribeCurrentRSVP() {
if (rsvpListener != null) {
rsvpListener();
rsvpListener = null;
}
rsvpYes.className = '';
rsvpNo.className = '';
}