-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
585 lines (511 loc) · 18.1 KB
/
Copy pathscript.js
File metadata and controls
585 lines (511 loc) · 18.1 KB
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
// Get the modal overlay and trigger button
const commentModalOverlay = document.getElementById('comment-modal-overlay');
const triggerBtn = document.querySelector('.comment-box-mld');
// These will be assigned after the modal is opened
let commentBox, textarea, charCounter, submitBtn, commentsSection, commentCountEl, sortSelect, nameInput, emailInput, REPLY_PARENT_ID, REPLY_IMMEDIATE_ID;
let REPLY_TO_NAME = '';
let MENTION_PREFIX = '';
// Open modal when trigger button is clicked
if (triggerBtn) {
triggerBtn.addEventListener('click', () => {
commentModalOverlay.classList.add('active');
initCommentBox();
});
}
// Close modal when close button is clicked
const closeBtn = document.querySelector('.comment-close-btn');
if (closeBtn) {
closeBtn.addEventListener('click', () => {
commentModalOverlay.classList.remove('active');
});
}
// Close modal when clicking outside
commentModalOverlay.addEventListener('click', (e) => {
if (e.target === commentModalOverlay) {
commentModalOverlay.classList.remove('active');
}
});
// Scroll to top button
const scrollToTopBtn = document.querySelector('.scroll-to-top-btn');
if (scrollToTopBtn) {
scrollToTopBtn.addEventListener('click', () => {
const modalBody = document.getElementById('comment-modal-body');
if (modalBody) {
modalBody.scrollTo({ top: 0, behavior: 'smooth' });
}
});
}
const MAX_CHARS = 500;
const MIN_NAME_LENGTH = 3;
const MAX_NAME_LENGTH = 15;
const getTopicFromMeta = () => {
const metaTag = document.querySelector('meta[name="comment-topic"]');
if (metaTag && metaTag.content && metaTag.content.trim() !== '') {
return metaTag.content.trim();
}
if (commentBox && commentBox.dataset.topic) {
return commentBox.dataset.topic;
}
const path = window.location.pathname;
const cleanPath = path.replace(/\/index\.html$/i, '').replace(/^\//, '') || 'home';
return cleanPath.replace(/\//g, '-');
};
let topic;
let isAdmin = false;
let commentsEnabled = true;
function initCommentBox() {
// Only initialize once
if (commentBox) return;
commentBox = document.querySelector('.comment-box');
if (!commentBox) return;
textarea = commentBox.querySelector('textarea');
charCounter = commentBox.querySelector('.char-counter');
submitBtn = commentBox.querySelector('.submit-btn');
commentsSection = commentBox.querySelector('.comments-section');
commentCountEl = commentBox.querySelector('.comment-count');
sortSelect = commentBox.querySelector('select');
nameInput = commentBox.querySelector('.name-input');
emailInput = commentBox.querySelector('.email-input');
REPLY_PARENT_ID = commentBox.querySelector('.reply-parent-id');
REPLY_IMMEDIATE_ID = commentBox.querySelector('.reply-immediate-id');
topic = getTopicFromMeta();
// Add event listeners
textarea.addEventListener('input', updateCharCounter);
submitBtn.addEventListener('click', submitComment);
sortSelect.addEventListener('change', () => fetchComments(sortSelect.value));
textarea.addEventListener('keydown', handleBackspace);
nameInput.addEventListener('input', handleNameInput);
nameInput.addEventListener('blur', validateName);
checkCommentStatus();
}
let badWords = [];
fetch('profanity.json')
.then(res => res.json())
.then(data => {
badWords = data.map(word => word.toLowerCase());
})
.catch(err => console.error('Failed to load profanity.json:', err));
// change according to your link
function checkCommentStatus() {
// PASTEYOUR LINK LIKE THIS fetch(`PASTE_YOUR_LINK?action=checkStatus&topic=${encodeURIComponent(topic)}`)
fetch(`https://script.google.com/macros/s/AKfycbyvLjheYK-3NOFHVN01ATl2KftiENYy58sM9IA6QGDroiemY406KPuRp_BFvHE-muyG/exec?action=checkStatus&topic=${encodeURIComponent(topic)}`)
.then(res => res.json())
.then(data => {
commentsEnabled = data.commentsEnabled !== false;
if (!commentsEnabled) {
disableCommentInputs();
}
fetchComments(sortSelect.value || 'desc');
})
.catch(err => {
console.error('Failed to check comment status:', err);
commentsEnabled = true;
fetchComments(sortSelect.value || 'desc');
});
}
function disableCommentInputs() {
textarea.disabled = true;
nameInput.disabled = true;
emailInput.disabled = true;
submitBtn.disabled = true;
textarea.placeholder = 'Comments are currently disabled';
const inputWrappers = commentBox.querySelectorAll('.input-wrapper');
inputWrappers.forEach(wrapper => {
wrapper.style.display = 'none';
});
submitBtn.style.display = 'none';
if (charCounter && charCounter.parentElement) {
charCounter.parentElement.style.display = 'none';
}
const existingNotice = commentBox.querySelector('.comment-disabled-notice');
if (existingNotice) existingNotice.remove();
const noticeDiv = document.createElement('div');
noticeDiv.className = 'comment-disabled-notice';
noticeDiv.innerHTML = `
<div class="comment-disabled-notice-icon">
<i class="fas fa-comment-slash"></i>
</div>
<div class="comment-disabled-notice-content">
<div class="comment-disabled-notice-title">Comments Closed</div>
<div class="comment-disabled-notice-text">
New comments are not being accepted at this time. Existing comments are displayed below for reference.
</div>
</div>
`;
const formContainer = commentBox.querySelector('.comment-form') || textarea.closest('div');
if (formContainer) {
formContainer.style.display = 'none';
formContainer.parentNode.insertBefore(noticeDiv, formContainer);
} else {
commentBox.insertBefore(noticeDiv, commentsSection);
}
}
function handleNameInput(e) {
const value = e.target.value.replace(/[^a-zA-Z\s]/g, '');
e.target.value = value;
clearTimeout(nameInput.validationTimer);
nameInput.validationTimer = setTimeout(validateName, 500);
}
function validateName() {
if (isAdmin) {
nameInput.style.borderColor = '';
const warning = document.getElementById('name-warning');
if (warning) warning.remove();
return true;
}
const name = nameInput.value.trim();
let warningMessage = '';
if (!name) {
warningMessage = 'Please enter your first name';
} else if (name.length < MIN_NAME_LENGTH) {
warningMessage = `Name must be at least ${MIN_NAME_LENGTH} characters`;
} else if (name.length > MAX_NAME_LENGTH) {
warningMessage = `Name must be no more than ${MAX_NAME_LENGTH} characters`;
} else if (name.split(/\s+/).length > 1) {
const firstName = name.split(/\s+/)[0];
const surname = name.substring(firstName.length).trim();
warningMessage = `Please use only your first name (e.g., "${firstName}") - no surnames like "${surname}"`;
} else if (badWords.some(word => name.toLowerCase().includes(word.toLowerCase()))) {
warningMessage = 'Please use appropriate language in your name';
}
if (warningMessage) {
nameInput.style.borderColor = 'red';
if (!document.getElementById('name-warning')) {
const warning = document.createElement('div');
warning.id = 'name-warning';
warning.style.color = 'red';
warning.style.marginTop = '5px';
warning.style.fontSize = '0.8em';
warning.style.lineHeight = '1.2';
nameInput.closest('.input-wrapper').appendChild(warning);
}
document.getElementById('name-warning').textContent = warningMessage;
return false;
} else {
nameInput.style.borderColor = '';
const warning = document.getElementById('name-warning');
if (warning) warning.remove();
return true;
}
}
function updateCharCounter() {
const remaining = MAX_CHARS - textarea.value.length;
charCounter.textContent = `${textarea.value.length} / ${MAX_CHARS}`;
charCounter.style.color = remaining < 0 ? 'red' : '';
if (textarea.value.trim() === '' && REPLY_TO_NAME) {
clearReply();
}
}
function resetCharCounter() {
charCounter.textContent = `0 / ${MAX_CHARS}`;
charCounter.style.color = '';
}
function maskProfanity(text) {
let maskedText = text;
badWords.forEach(word => {
const safeWord = word.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
const regex = new RegExp(`\\b${safeWord}\\b`, 'gi');
maskedText = maskedText.replace(regex, match => '*'.repeat(match.length));
});
return maskedText;
}
function clearReply() {
REPLY_PARENT_ID.value = '';
REPLY_IMMEDIATE_ID.value = '';
REPLY_TO_NAME = '';
MENTION_PREFIX = '';
textarea.placeholder = 'Share your thoughts...';
}
function handleBackspace(e) {
if (e.key === 'Backspace' && REPLY_TO_NAME) {
const text = textarea.value;
const cursorPos = textarea.selectionStart;
if (cursorPos <= MENTION_PREFIX.length &&
text.startsWith(MENTION_PREFIX.substring(0, cursorPos))) {
clearReply();
}
}
}
function submitComment() {
if (!commentsEnabled) {
VanillaToasts.create({
title: 'Comments Disabled',
text: 'Comments are currently disabled for this topic.',
type: 'warning',
timeout: 4000,
positionClass: 'bottomLeft'
});
return;
}
let message = textarea.value.trim();
const name = nameInput.value.trim();
if (!isAdmin) {
if (!name) {
nameInput.focus();
VanillaToasts.create({
title: 'Missing Name',
text: 'Please enter your first name.',
type: 'warning',
timeout: 3000,
positionClass: 'bottomLeft'
});
return;
}
if (!validateName()) {
nameInput.focus();
return;
}
}
if (REPLY_TO_NAME) {
message = message.replace(new RegExp(`^@${REPLY_TO_NAME}\\s*`), '').trim();
}
if (!message) {
VanillaToasts.create({
title: 'Empty Comment',
text: 'Please enter a comment before posting.',
type: 'warning',
timeout: 4000
});
return;
}
if (message.length > MAX_CHARS) {
VanillaToasts.create({
title: 'Too Long',
text: `Comment exceeds the ${MAX_CHARS}-character limit.`,
type: 'error',
timeout: 4000
});
return;
}
message = maskProfanity(message);
const formData = new URLSearchParams();
formData.append('topic', topic);
formData.append('name', name);
formData.append('message', message);
formData.append('parentId', REPLY_PARENT_ID.value || '');
formData.append('immediateId', REPLY_IMMEDIATE_ID.value || '');
formData.append('isReply', REPLY_PARENT_ID.value ? 'true' : 'false');
formData.append('replyToName', REPLY_TO_NAME || '');
formData.append('email', emailInput.value.trim());
submitBtn.disabled = true;
submitBtn.innerHTML = `<span class="spinner"></span> Posting...`;
//PASTE_YOUR_LINK HERE
fetch('https://script.google.com/macros/s/AKfycbyvLjheYK-3NOFHVN01ATl2KftiENYy58sM9IA6QGDroiemY406KPuRp_BFvHE-muyG/exec', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
body: formData.toString(),
})
.then(res => res.json())
.then(data => {
if (data.success) {
isAdmin = data.isAdmin === true || data.isAdmin === 'true';
if (isAdmin) {
nameInput.classList.add('verified');
}
textarea.value = '';
nameInput.value = '';
emailInput.value = '';
resetCharCounter();
clearReply();
fetchComments(sortSelect.value);
} else {
VanillaToasts.create({
title: 'Post Failed',
text: `Error: ${data.error || 'Unknown error'}`,
type: 'error',
timeout: 5000
});
}
})
.catch(err => {
VanillaToasts.create({
title: 'Network Error',
text: err.message,
type: 'error',
timeout: 5000
});
})
.finally(() => {
submitBtn.disabled = false;
submitBtn.innerHTML = '<i class="fas fa-paper-plane"></i> Post';
});
}
function fetchComments(order = 'desc') {
if (!commentsSection) return;
commentsSection.innerHTML = Array(3).fill(`
<div class="skeletoncom">
<div class="skeletoncom-circle"></div>
<div class="skeletoncom-lines">
<div class="skeletoncom-line medium"></div>
<div class="skeletoncom-line short"></div>
</div>
</div>
`).join('');
// change according to your link fetch(`PASTE_YOUR_LINK_LIKE_THIS?topic=${encodeURIComponent(topic)}`)
fetch(`https://script.google.com/macros/s/AKfycbyvLjheYK-3NOFHVN01ATl2KftiENYy58sM9IA6QGDroiemY406KPuRp_BFvHE-muyG/exec?topic=${encodeURIComponent(topic)}`)
.then(res => res.json())
.then(data => {
if (!Array.isArray(data)) {
commentsSection.innerHTML = 'Failed to load comments.';
return;
}
data.sort((a, b) => order === 'asc' ? a.sortIndex - b.sortIndex : b.sortIndex - a.sortIndex);
const commentMap = new Map();
data.forEach(c => commentMap.set(c.sortIndex, { ...c, replies: [] }));
data.forEach(c => {
if (c.isReply && c.parentId) {
const parent = commentMap.get(Number(c.parentId));
if (parent) parent.replies.push(c);
}
});
const rootComments = Array.from(commentMap.values()).filter(c => !c.isReply || !c.parentId);
document.querySelectorAll('.comment-count').forEach(el => {
el.textContent = data.length;
});
renderComments(rootComments);
})
.catch(() => {
commentsSection.innerHTML = 'Failed to load comments.';
});
}
function renderComments(comments) {
commentsSection.innerHTML = '';
comments.forEach(c => {
const commentEl = createCommentElement(c);
commentsSection.appendChild(commentEl);
});
}
function createCommentElement(comment) {
const div = document.createElement('div');
div.classList.add('comment');
if (comment.isReply === 'true' || comment.isReply === true) {
div.classList.add('reply');
}
const header = document.createElement('div');
header.classList.add('comment-header');
const avatar = document.createElement('div');
avatar.classList.add('comment-avatar');
const isAdminUser = comment.isAdmin === true || comment.isAdmin === 'true';
//CHANGE AVATAR PFP
if (isAdminUser) {
avatar.innerHTML = '<img src="https://avatars.githubusercontent.com/u/123620381?v=4&size=64" class="comment-avatar" alt="Admin Avatar">';
} else {
avatar.innerHTML = `
<div style="
width: 40px;
height: 40px;
border-radius: 50%;
background-color: ${stringToColor(comment.name || 'Anonymous')};
color: white;
display: flex;
justify-content: center;
align-items: center;
font-weight: bold;
font-size: 18px;
">
${getInitials(comment.name || 'A')}
</div>
`;
}
header.appendChild(avatar);
const userDiv = document.createElement('div');
userDiv.classList.add('comment-user');
userDiv.innerHTML = `
<strong>
${escapeHtml(comment.name)}
${isAdminUser ? '<i class="fas fa-check-circle verified-badge" title="Verified"></i>' : ''}
</strong>
<span class="time">${formatDate(comment.sortIndex)}</span>
`;
header.appendChild(userDiv);
div.appendChild(header);
const contentDiv = document.createElement('div');
contentDiv.classList.add('comment-content');
const p = document.createElement('p');
if (comment.isReply === 'true' || comment.isReply === true) {
const mentionSpan = document.createElement('span');
mentionSpan.classList.add('mention');
mentionSpan.textContent = `@${escapeHtml(comment.replyToName || 'Unknown')}`;
p.appendChild(mentionSpan);
p.appendChild(document.createTextNode(' ' + escapeHtml(comment.message)));
} else {
p.textContent = escapeHtml(comment.message);
}
contentDiv.appendChild(p);
div.appendChild(contentDiv);
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('comment-btn-container');
buttonContainer.style.display = 'flex';
buttonContainer.style.gap = '15px';
buttonContainer.style.alignItems = 'center';
buttonContainer.style.marginTop = '10px';
if (commentsEnabled) {
const replyBtn = document.createElement('button');
replyBtn.classList.add('reply-btn');
replyBtn.innerHTML = '<i class="fas fa-reply"></i> Reply';
replyBtn.addEventListener('click', () => {
REPLY_PARENT_ID.value = comment.parentId || comment.sortIndex;
REPLY_IMMEDIATE_ID.value = comment.sortIndex;
REPLY_TO_NAME = comment.name;
MENTION_PREFIX = `@${comment.name}`;
textarea.focus();
textarea.placeholder = `Replying to @${comment.name}...`;
textarea.value = MENTION_PREFIX + ' ';
textarea.selectionStart = textarea.selectionEnd = textarea.value.length;
});
buttonContainer.appendChild(replyBtn);
}
if (comment.replies?.length > 0) {
const repliesContainer = document.createElement('div');
repliesContainer.classList.add('replies');
repliesContainer.style.display = 'none';
comment.replies.forEach(reply => {
repliesContainer.appendChild(createCommentElement(reply));
});
const toggleBtn = document.createElement('button');
toggleBtn.classList.add('toggle-replies-btn');
toggleBtn.innerHTML = `<i class="fas fa-comments"></i> <span>Show Replies (${comment.replies.length})</span>`;
toggleBtn.addEventListener('click', () => {
const isHidden = repliesContainer.style.display === 'none';
repliesContainer.style.display = isHidden ? 'block' : 'none';
toggleBtn.querySelector('span').textContent =
isHidden ? `Hide Replies (${comment.replies.length})` : `Show Replies (${comment.replies.length})`;
});
buttonContainer.appendChild(toggleBtn);
div.appendChild(buttonContainer);
div.appendChild(repliesContainer);
} else {
div.appendChild(buttonContainer);
}
return div;
}
function getInitials(name) {
const names = name.trim().split(' ');
return names.length === 1
? names[0].charAt(0).toUpperCase()
: (names[0].charAt(0) + names[names.length - 1].charAt(0)).toUpperCase();
}
function stringToColor(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
return `hsl(${hash % 360}, 60%, 70%)`;
}
function formatDate(timestamp) {
return new Date(timestamp).toLocaleString('en-US', {
month: 'long',
day: 'numeric',
year: 'numeric',
hour: 'numeric',
minute: '2-digit',
hour12: true
});
}
function escapeHtml(text) {
return text
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
}