forked from anuragverma108/SwapReads
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.js
123 lines (108 loc) · 3.77 KB
/
chat.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
// Import Firebase SDK components
import { initializeApp } from "firebase/app";
import { getFirestore, collection, addDoc, query, onSnapshot, orderBy } from "firebase/firestore";
// Your Firebase configuration
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID",
measurementId: "YOUR_MEASUREMENT_ID"
};
// Initialize Firebase and Firestore
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
// DOM Elements
const startChatBtn = document.getElementById('start-chat');
const sendMessageBtn = document.getElementById('send-message');
const usernameInput = document.getElementById('username');
const messageInput = document.getElementById('message');
const userInputDiv = document.getElementById('user-input');
const chatBoxDiv = document.getElementById('chat-box');
const messagesDiv = document.getElementById('messages');
const backButton = document.getElementById('backbutton');
const navbarToggleBtn = document.querySelector('.navbar-toggle');
const navbarMenu = document.getElementById('navbarMenu');
// Event Listeners
startChatBtn.addEventListener('click', startChat);
sendMessageBtn.addEventListener('click', sendMessage);
messageInput.addEventListener('keypress', handleEnterPress);
backButton.addEventListener('click', handleBack);
navbarToggleBtn.addEventListener('click', toggleNav);
document.addEventListener('click', handleOutsideClick);
document.querySelectorAll('.navbar-link').forEach(link => {
link.addEventListener('click', closeNavMenu);
});
// Functions
function startChat() {
const username = usernameInput.value.trim();
if (username) {
localStorage.setItem('username', username);
userInputDiv.style.display = 'none';
chatBoxDiv.style.display = 'block';
loadMessages();
} else {
alert('Please enter a username');
}
}
function handleEnterPress(e) {
if (e.key === 'Enter') {
sendMessage();
}
}
function handleBack(e) {
e.preventDefault();
chatBoxDiv.style.display = 'none';
userInputDiv.style.display = 'block';
localStorage.removeItem('username');
}
async function sendMessage() {
const messageText = messageInput.value.trim();
if (messageText) {
const username = localStorage.getItem('username');
const timestamp = new Date().toISOString();
try {
await addDoc(collection(db, 'messages'), {
username,
messageText,
timestamp
});
messageInput.value = '';
} catch (error) {
console.error("Error adding message: ", error);
}
}
}
function loadMessages() {
const q = query(collection(db, 'messages'), orderBy('timestamp', 'asc'));
onSnapshot(q, (querySnapshot) => {
messagesDiv.innerHTML = '';
querySnapshot.forEach((doc) => {
displayMessage(doc.data());
});
});
}
function displayMessage({ username, messageText, timestamp }) {
const messageDiv = document.createElement('div');
messageDiv.className = 'message';
messageDiv.innerHTML = `
<span class="username">${username}</span>:
${messageText}
<span class="timestamp">(${new Date(timestamp).toLocaleString()})</span>
`;
messagesDiv.appendChild(messageDiv);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
function toggleNav() {
navbarMenu.classList.toggle('active');
}
function closeNavMenu() {
navbarMenu.classList.remove('active');
}
function handleOutsideClick(event) {
if (!navbarMenu.contains(event.target) && !navbarToggleBtn.contains(event.target)) {
navbarMenu.classList.remove('active');
}
}