-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
414 lines (368 loc) · 14.1 KB
/
script.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
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
let dataState = {
loading: true,
commentData: null,
};
// Function to fetch data from JSON file
async function fetchData() {
try {
const response = await fetch('data.json');
if (!response.ok) {
throw new Error('Network response was not ok');
}
dataState.commentData = await response.json();
dataState.loading = false;
} catch (error) {
console.error('Error loading JSON:', error);
dataState.loading = false;
} finally {
if (dataState.loading) {
console.log('Loading...');
} else {
renderComments();
}
}
}
// Function to render comments
function renderComments() {
const container = document.getElementById('container');
const { comments, currentUser } = dataState.commentData;
comments.forEach((comment) => {
const commentItem = createCommentHTML(comment, currentUser);
container.insertAdjacentHTML('beforeend', commentItem);
});
attachEventListeners();
}
// Function to create HTML for a single comment
function createCommentHTML(comment, currentUser) {
const { id, content, createdAt, score, replies, user } = comment;
const commentItem = `
<div class="commentList g-20" id="commentList-${id}">
<div class="commentContainer" id="comment-${id}">
<div class="post comment card ${user.username}">
<div class="profile">
<img src="${user.image.webp}" alt="" />
<p class="userName" id="profile-${id}">${user.username}</p>
<span class="timeStamp">${createdAt}</span>
</div>
<div class="commentText">
<p>${content}</p>
</div>
<div class="likeDislike">
<button class="like" type="button" id="like-${id}">+</button>
<span class="count" id="score-${id}">${score}</span>
<button class="dislike" type="button" id="dislike-${id}">-</button>
</div>
${
currentUser.username !== user.username
? `<button class="replyTriggerBtn" type="button" id="commentReplyBtn-${id}">
<i class="fa-solid fa-reply"></i>
Reply
</button>`
: `<div class="editDeleteContainer g-20">
<button class="editDelete edit" type="button" id="editBtn-${id}">
<i class="fa-solid fa-pencil"></i>
Edit
</button>
<button class="editDelete delete" type="button" id="deleteBtn-${id}">
<i class="fa-solid fa-trash"></i>
Delete
</button>
</div>`
}
</div>
<!-- List of Replies -->
<div class="commentReplyListCover">
<span class="line"></span>
<div class="commentReplyListContainer g-10" id="commentReplyListContainer-${id}">
${
replies
? replies
.map(
({ id, content, createdAt, score, user }) => `
<div class="comment commentReplyList card ${
user.username
}" id="comment-${id}">
<div class="profile">
<img src="${user.image.webp}" alt="${user.username}" />
<p class="userName" id="profile-${id}">${
user.username
}</p>
<span class="timeStamp">${createdAt}</span>
</div>
<div class="commentText">
<p>${content}</p>
</div>
<div class="likeDislike">
<button class="like" type="button" id="like-${id}">+</button>
<span class="count" id="score-${id}">${score}</span>
<button class="dislike" type="button" id="dislike-${id}">-</button>
</div>
${
currentUser.username !== user.username
? `<button class="replyTriggerBtn" type="button" id="commentReplyBtn-${id}">
<i class="fa-solid fa-reply"></i>
Reply
</button>`
: `<div class="editDeleteContainer g-20">
<button class="editDelete edit" type="button" id="editBtn-${id}">
<i class="fa-solid fa-pencil"></i>
Edit
</button>
<button class="editDelete delete" type="button" id="deleteBtn-${id}">
<i class="fa-solid fa-trash"></i>
Delete
</button>
</div>`
}
</div>`
)
.join('')
: ''
}
</div>
</div>
<!-- List of Replies Ends -->
</div>
</div>`;
return commentItem;
}
// Function to attach event listeners to buttons
function attachEventListeners() {
document.querySelectorAll('.edit').forEach((button) => {
button.addEventListener('click', (e) => handleEdit(e));
});
document.querySelectorAll('.delete').forEach((button) => {
button.addEventListener('click', (e) => handleDelete(e));
});
// Attach event listeners to reply buttons
document.querySelectorAll('.post .replyTriggerBtn').forEach((button) => {
const commentId = button.id.split('-')[1];
button.addEventListener('click', () => handleReply(commentId));
});
document
.querySelectorAll('.commentReplyListCover .replyTriggerBtn')
.forEach((button) => {
const replyId = button.id.split('-')[1];
button.addEventListener('click', () => handleReply(replyId));
});
document.querySelectorAll('.like').forEach((button) => {
const likeId = button.id.split('-')[1];
button.addEventListener('click', () => handleLike(likeId));
});
document.querySelectorAll('.dislike').forEach((button) => {
const dislikeId = button.id.split('-')[1];
button.addEventListener('click', () => handleDislike(dislikeId));
});
}
// Function to handle editing a comment
function handleEdit(e) {
const editBtn = e.target;
const id = editBtn.id.split('-')[1];
const postToEdit = document.getElementById(`comment-${id}`);
const deleteBtn = postToEdit.querySelector('.delete');
const commentText = postToEdit.querySelector('.commentText p');
commentText.contentEditable = true;
commentText.classList.add('border');
commentText.insertAdjacentHTML(
'afterend',
`<button class ='updateBtn' id="updatePost-${id}">Update</button>`
);
const updateBtn = postToEdit.querySelector(`#updatePost-${id}`);
// New text
commentText.addEventListener('keyup', () => {
handleContentInput(commentText.innerText, updateBtn);
});
updateBtn.addEventListener('click', () => handleUpdate(e));
e.target.disabled = true;
deleteBtn.disabled = true;
function handleUpdate(e) {
if (handleContentInput(commentText.innerText, e.target)) {
commentText.classList.remove('border');
commentText.contentEditable = false;
editBtn.disabled = false;
deleteBtn.disabled = false;
updateBtn.remove();
}
console.log(handleContentInput(commentText.innerText, e.target));
}
}
// Function to handle deleting a comment
function handleDelete(e) {
const id = e.target.id.split('-')[1];
const postToBeDeleted = document.getElementById(`comment-${id}`);
getDeleteConfirmation(function (response) {
if (response === 'yes') {
const deleteConfirmContainer = document.querySelector(
'.deleteConfirmContainer'
);
deleteConfirmContainer.remove();
postToBeDeleted.remove();
} else if (response === 'no') {
const deleteConfirmContainer = document.querySelector(
'.deleteConfirmContainer'
);
deleteConfirmContainer.remove();
}
});
}
function handleLike(e) {
if (!document.getElementById(`like-${e}`).disabled) {
let score = document.getElementById(`score-${e}`);
score.innerText = Number(score.innerText) + 1;
document.getElementById(`like-${e}`).disabled = true;
document.getElementById(`dislike-${e}`).disabled = false;
}
}
function handleDislike(e) {
if (!document.getElementById(`dislike-${e}`).disabled) {
let score = document.getElementById(`score-${e}`);
score.innerText = Number(score.innerText) - 1;
document.getElementById(`dislike-${e}`).disabled = true;
document.getElementById(`like-${e}`).disabled = false;
}
}
// Reply input checker
function handleContentInput(content, actionButton) {
if (content.trim().length >= 2) {
actionButton.disabled = false;
return true;
} else {
actionButton.disabled = true;
}
}
// Function to handle replying to a comment
function handleReply(id) {
const { currentUser } = dataState.commentData;
const buttonElement = document.getElementById(`commentReplyBtn-${id}`);
const replyInputs = document.querySelectorAll('.commentReply');
let postOwner = document.getElementById(`profile-${id}`).innerText;
let content = `<span>@${postOwner}</span>`;
let commentList = document.getElementById(`commentList-${id}`);
const replyCommentReply = buttonElement.parentElement;
const currentUserReply = `
<div class="card commentReply fadeIn" id="replyInputContainer${id}">
<img src="${currentUser.image.webp}" alt="${currentUser.username}" />
<div class="textarea" role="textbox" contenteditable title="commentReply" id="postContent-${id}">
${content}
</div>
<button type="button" id="postReplyBtn-${id}" disabled>REPLY</button>
</div>`;
// Remove reply input on all posts
replyInputs.forEach((notCommentToReply) => {
notCommentToReply.parentElement.removeChild(notCommentToReply);
});
// Disable reply button on comment reply
document.querySelectorAll('.replyTriggerBtn').forEach((button) => {
buttonElement.id === button.id
? (buttonElement.disabled = true)
: (button.disabled = false);
});
// Add reply input to comment's reply button clicked
replyCommentReply.className.includes('commentReplyList')
? replyCommentReply.parentElement.parentElement.parentElement.insertAdjacentHTML(
'beforeend',
currentUserReply
)
: commentList.insertAdjacentHTML('beforeend', currentUserReply);
const postReplyBtn = document.getElementById(`postReplyBtn-${id}`);
const postContent = document.getElementById(`postContent-${id}`);
// Scroll to the newly added reply input
postContent.scrollIntoView({ behavior: 'smooth' });
postContent.addEventListener('keyup', (e) => {
content = e.target.innerText;
handleContentInput(content, postReplyBtn);
});
// Add event listener to send comment button
postReplyBtn.addEventListener('click', (e) => handlePost(e, content));
// Fuction to post a comment
const handlePost = (e, content) => {
const parentElement = e.target.parentElement.parentElement; // Find the parent element
const replyList = document.getElementById(
`commentReplyListContainer-${parentElement.id.split('-')[1]}`
);
let lastCommentid =
replyList.lastElementChild === null
? 0
: ++replyList.lastElementChild.id.split('-')[1];
const currentUserReply = `
<div class="comment commentReplyList card ${
currentUser.username
}" id="comment-${lastCommentid}">
<div class="profile">
<img src="${currentUser.image.webp}" alt="${currentUser.username}" />
<p class="userName" id="profile-${currentUser.username}">${
currentUser.username
}</p>
<span class="timeStamp">A week ago</span>
</div>
<div class="commentText">
<p>${content}</p>
</div>
<div class="likeDislike">
<button class="like" type="button" id="like-${lastCommentid}">+</button>
<span class="count" id="score-${lastCommentid}">0</span>
<button class="dislike" type="button" id="dislike-${lastCommentid}">-</button>
</div>
<div class="editDeleteContainer g-20">
<button class="editDelete edit" type="button" id="editBtn-${lastCommentid}">
<i class="fa-solid fa-pencil"></i>
Edit
</button>
<button class="editDelete delete" type="button" id="deleteBtn-${lastCommentid}">
<i class="fa-solid fa-trash"></i>
Delete
</button>
</div>
</div>`;
if (content === undefined) {
postReplyBtn.disabled = true;
} else {
if (handleContentInput(postContent.innerText, postReplyBtn)) {
replyList.insertAdjacentHTML('beforeend', currentUserReply);
parentElement.removeChild(e.target.parentElement);
buttonElement.disabled = false;
document
.getElementById(`deleteBtn-${lastCommentid}`)
.addEventListener('click', (e) => handleDelete(e));
document
.getElementById(`editBtn-${lastCommentid}`)
.addEventListener('click', (e) => handleEdit(e));
document
.getElementById(`like-${lastCommentid}`)
.addEventListener('click', () => handleLike(lastCommentid));
document
.getElementById(`dislike-${lastCommentid}`)
.addEventListener('click', () => handleDislike(lastCommentid));
} else {
alert("Can't be empty");
}
}
};
}
function getDeleteConfirmation(callback) {
document.getElementById('container').insertAdjacentHTML(
'beforeEnd',
`<div class="deleteConfirmContainer">
<div class="card deleteConfirm">
<h3>Delete comment</h3>
<p>
Are you sure you want to delete this comment? This will remove the
comment and can't be undone
</p>
<div class="confirmOption" id='confirmOption'>
<button id='no'>NO,CANCEL</button>
<button id='yes'>YES, DELETE</button>
</div>
</div>
</div>`
);
const confirmOption = document.getElementById('confirmOption');
confirmOption.addEventListener('click', (e) => {
const buttonId = e.target.id;
if (callback && typeof callback === 'function') {
callback(buttonId);
}
});
}
// Call the fetchData function when you want to initiate the data fetch
fetchData();