forked from anuragverma108/SwapReads
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.js
134 lines (119 loc) · 4.68 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
124
125
126
127
128
129
130
131
132
133
// Import Firebase SDK components
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-app.js";
import { getFirestore, collection, addDoc, query, onSnapshot, orderBy } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore.js";
// 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');
// Start Chat Button Event
startChatBtn.addEventListener('click', () => {
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');
}
});
// Send Message Button Event
sendMessageBtn.addEventListener('click', sendMessage);
messageInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
sendMessage();
}
});
// Back Button Event
backButton.addEventListener('click', (e) => {
e.preventDefault(); // Prevent default link behavior
chatBoxDiv.style.display = 'none';
userInputDiv.style.display = 'block';
localStorage.removeItem('username'); // Optionally, clear the stored username
});
// Function to send a message to Firestore
async function sendMessage() {
const messageText = messageInput.value.trim();
if (messageText) {
const username = localStorage.getItem('username');
const timestamp = new Date().toISOString();
try {
// Add message to Firestore
await addDoc(collection(db, 'messages'), {
username: username,
messageText: messageText,
timestamp: timestamp
});
messageInput.value = ''; // Clear the input field after sending
} catch (error) {
console.error("Error adding message: ", error);
}
}
}
// Function to load and display messages from Firestore
function loadMessages() {
const q = query(collection(db, 'messages'), orderBy('timestamp', 'asc'));
onSnapshot(q, (querySnapshot) => {
messagesDiv.innerHTML = ''; // Clear current messages
querySnapshot.forEach((doc) => {
const message = doc.data();
displayMessage(message);
});
});
}
// Function to display a message
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; // Auto-scroll to the latest message
}
// Function to toggle the navbar menu visibility
function toggleNav() {
const navbarMenu = document.getElementById('navbarMenu');
navbarMenu.classList.toggle('active');
}
// Adding event listener to the toggle button
const navbarToggleBtn = document.querySelector('.navbar-toggle');
navbarToggleBtn.addEventListener('click', toggleNav);
// Adding event listeners to navbar links to close the menu on click
const navbarLinks = document.querySelectorAll('.navbar-link');
navbarLinks.forEach(link => {
link.addEventListener('click', () => {
const navbarMenu = document.getElementById('navbarMenu');
if (navbarMenu.classList.contains('active')) {
navbarMenu.classList.remove('active');
}
});
});
// Adding event listener to the document to close the menu when clicking outside
document.addEventListener('click', (event) => {
const navbarMenu = document.getElementById('navbarMenu');
const toggleBtn = document.querySelector('.navbar-toggle');
if (!navbarMenu.contains(event.target) && !toggleBtn.contains(event.target)) {
navbarMenu.classList.remove('active');
}
});