-
Notifications
You must be signed in to change notification settings - Fork 0
/
scripts.js
269 lines (235 loc) · 10.6 KB
/
scripts.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
$(document).ready(function() {
// Function to fetch data from Google Sheets
function fetchData() {
fetch('https://script.google.com/macros/s/AKfycbx7tUfYv9-ikirBOEHU3FCmPEme-gyIylBEyTk8ijIK1N95ehz-Gc_wIoK_kpRZ9r2C/exec')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
const postsContainer = $('#postsContainer');
const isScrolledToBottom = postsContainer[0].scrollHeight - postsContainer.scrollTop() === postsContainer.outerHeight();
// Clear previous messages
postsContainer.empty();
// Iterate through the data array to create HTML elements
data.forEach(post => {
const postElement = $('<div>').addClass('message');
let userColor = getUserColor(post.name); // Get user's color based on name
const storedUsername = localStorage.getItem('username');
if (storedUsername===post.name) {
// If username is not stored, prompt user to input their name
postElement.html(`
<fieldset style=" border:5px solid ${userColor}; border-top-right-radius: 10px; border-top-left-radius: 10px; border-bottom-left-radius: 10px;padding:5px; float: right; width:85%; margin-top:5px;margin-bottom:5px;background-color: ${userColor+"20"}; ">
<legend style="color:#fff;background-color: ${userColor+"50"}; padding: 5px ; border-top-left-radius: 10px; border-bottom-right-radius: 10px; float:right;" >${post.name} <i class="fa fa-check-double"></i></legend>
<div style="">
<strong>
<h3 style="color:#383838;padding:5px;">${post.message} </h3>
</strong></div>
</fieldset>
`);
} else {
// If username is stored, use it to send messages
postElement.html(`
<fieldset style=" border:5px solid ${userColor}; border-top-right-radius: 10px; border-top-left-radius: 10px;width:85%; border-bottom-right-radius: 10px;padding:5px;display:block;background-color: ${userColor+"20"};">
<legend style="color:#fff;background-color: ${userColor+"50"}; padding: 5px ; border-bottom-left-radius: 10px; border-top-right-radius: 10px;position:absolute;">${post.name} <i class="fa fa-check-double"></i></legend>
<div style="margin-top:30px">
<strong>
<h3 style="color:#383838;padding:5px;">${post.message} </h3>
</strong></div>
</fieldset>
`);
}
postsContainer.append(postElement);
});
// Scroll to the bottom if previously scrolled to the bottom
if (isScrolledToBottom) {
postsContainer.scrollTop(postsContainer[0].scrollHeight);
}
})
.catch(error => {
console.error('Error fetching data:', error);
// Display an error message using SweetAlert2
Swal.fire({
icon: 'error',
title: 'Connection Failure !',
text: 'You are not online. Please try again later.'
});
});
}
// Check if username is already stored in local storage
const storedUsername = localStorage.getItem('username');
if (!storedUsername) {
// If username is not stored, prompt user to input their name
promptForUsername();
} else {
// If username is stored, use it to send messages
sendMessage(storedUsername);
}
// Function to prompt user for username
function promptForUsername() {
Swal.fire({
icon: 'warning',
title: 'username',
showConfirmButton:false,
showCancelButton: false,
allowOutsideClick: false,
allowEscapeKey: false,
}).then((result) => {
if (result.isConfirmed) {
// Save username to local storage
localStorage.setItem('username', result.value);
// Send message with username
sendMessage(result.value);
}
});
console.log('Username prompt displayed.'); // Log when username prompt is displayed
}
// Function to generate a color based on the hash code of the name
function getUserColor(username) {
// Generate hash code
let hash = 0;
for (let i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + ((hash << 5) - hash);
}
// Convert hash code to hex color
let color = '#';
for (let i = 0; i < 3; i++) {
let value = (hash >> (i * 8)) & 0xFF;
color += ('00' + value.toString(16)).substr(-2);
}
return color;
}
// Function to send message with username
function sendMessage(username) {
// Handle form submission
$('#submitForm').submit(function(event) {
event.preventDefault(); // Prevent default form submission behavior
// Fetch data from the form
const formData = new FormData(this);
formData.append('name', username); // Append username to form data
// Get message from form data
const message = formData.get('message');
// Append the message to the chat window with the user's color
const postElement = $('<div>').addClass('message');
const userColor = getUserColor(username); // Get user's color based on name
// If username is not stored, prompt user to input their name
postElement.html(`
</fieldset>
<fieldset style=" border:5px solid ${userColor}; border-top-right-radius: 10px; border-top-left-radius: 10px; border-bottom-left-radius: 10px;padding:5px; float: right; width:85%; margin-top:5px;margin-bottom:5px;background-color: ${userColor+"20"}; ">
<legend style="color:#fff;background-color: ${userColor+"50"}; padding: 5px ; border-top-left-radius: 10px; border-bottom-right-radius: 10px; float:right;" >${username} <i class="fa fa-chevron-down"></i></legend>
<div style="">
<strong>
<h3 style="color:#383838;padding:5px;text-size-adjust: 100%;">${message} </h3>
</strong></div>
</fieldset>
`);
$('#postsContainer').append(postElement);
// Scroll to the bottom of the messages
setTimeout($('html, body').animate({ scrollTop: $('#postsContainer')[0].scrollHeight }, 'slow'),1000);
// Clear the message input
$('#messageInput').val('')
// Submit form data to the server
fetch(this.action, {
method: 'POST',
body: formData
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Optionally, you can handle successful submission here
})
.catch(error => {
console.error('Error submitting form:', error);
// Display an error message using SweetAlert2
Swal.fire({
icon: 'error',
title: 'Message is not sent',
text: 'Your internet connection is weak. Please try again later.',
text: 'Please try again later.'
});
});
});
}
// Fetch data initially and every 2 seconds
fetchData();
setInterval(fetchData, 4000);
// Scroll to bottom submit button
$('#sendButton').click(function() {
$('html, body').animate({ scrollTop: $('#postsContainer')[0].scrollHeight }, 'slow');
});
// Add scroll-to-bottom button functionality
$('#scrollButton').click(function() {
$('html, body').animate({ scrollTop: $('#postsContainer')[0].scrollHeight }, 'slow',);
return false;
});
// Show/hide scroll button based on scroll position
$(window).scroll(function() {
const $scrollButton = $('#scrollButton');
if ($(this).scrollTop() < 100) {
$scrollButton.fadeOut();
} else {
$scrollButton.fadeIn();
}
// Show/hide scroll button based on scroll position relative to the bottom
if ($(window).scrollTop() + $(window).height() == $(document).height()) {
$scrollButton.fadeIn();
} else {
$scrollButton.fadeOut();
}
// Show/hide scroll button based on scroll direction
if ($(this).scrollTop() < 100 && $(this).scrollTop() > previousScroll) {
$scrollButton.fadeIn();
} else {
$scrollButton.fadeOut();
}
previousScroll = ($(this).scrollTop());
});
var previousScroll = 1;
let scrollingDown = true; // Flag to track scrolling state
function scrollDown() {
if (scrollingDown) {
window.scrollBy(0, 15); // Scroll down by 15 pixels
requestAnimationFrame(scrollDown);
}
}
// Start the infinite scroll
scrollDown();
// Listen for scroll events
window.addEventListener("scroll", () => {
// Check if the user has scrolled up
if (window.scrollY < lastScrollY) {
// Stop the infinite scroll
scrollingDown = false;
}
lastScrollY = window.scrollY; // Update last scroll position
});
let lastScrollY = window.scrollY; // Initialize last scroll position
// Function to replace special characters with HTML entities
function replaceSpecialCharacters(message) {
// Define the replacements
const replacements = {
"<": "<",
">": ">"
// Add more replacements as needed
};
// Iterate through the replacements and replace characters in the message
for (const [key, value] of Object.entries(replacements)) {
message = message.replace(new RegExp(key, 'g'), value);
}
return message;
}
// Function to handle incoming messages and display them
function displayMessage(message) {
// Sanitize the message to replace special characters with HTML entities
const sanitizedMessage = replaceSpecialCharacters(message);
// Display the sanitized message in your chat interface
// Replace this line with your actual code to display the message
console.log(sanitizedMessage); // Example: Output the sanitized message to the console
}
// Example usage:
const originalMessage = "<style>";
displayMessage(originalMessage);
});