-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpost.html
More file actions
346 lines (300 loc) · 13.6 KB
/
Copy pathpost.html
File metadata and controls
346 lines (300 loc) · 13.6 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
<!DOCTYPE html>
<!-- root element -->
<html lang="en">
<!-- head section -->
<head>
<!-- metadata -->
<meta charset="UTF-8">
<!-- webpage title -->
<title>homepage</title>
<!-- stylesheet -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- bootstrap -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-FKyoEForCGlyvwx9Hj09JcYn3nv7wiPVlz7YYwJrWVcXK/BmnVDxM+D2scQbITxI"
crossorigin="anonymous"></script>
<!-- fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Hepta+Slab:[email protected]&family=Merriweather:ital,opsz,wght@0,18..144,300..900;1,18..144,300..900&display=swap"
rel="stylesheet">
<link
href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,[email protected],200..800&family=Hepta+Slab:[email protected]&family=Merriweather:ital,opsz,wght@0,18..144,300..900;1,18..144,300..900&display=swap"
rel="stylesheet">
<link rel="stylesheet" href="./styles.css">
</head>
<!-- body section -->
<body>
<header class="text-center py-4 border-bottom border-black">
<h1 class="fw-bold display-5">BLOG TITLE</h1>
</header>
<!-- navigation -->
<div id="navbar-container"></div>
<!-- main -->
<main>
<div class="container">
<div class="row">
<!-- Left Column - Main Post -->
<div class="col-md-8">
<section id="content" class="container my-4">
<div id="post">
<div class="bg-light-brown p-4">
<h2 id="blogTitle" class="fw-bold">Blog Title</h2>
<div class="d-flex justify-content-between align-items-center mt-3">
<div>
<small>By: <strong id="postAuthor">Name Lastname</strong></small>
<small id="postDate" class="ms-3">Posted on: <strong>January 1, 2025</strong></small>
<small class="ms-3">Comments: <strong>0</strong></small>
</div>
<div>
<!-- share button -->
<button id="shareBtn" class="btn btn-outline-primary">Share This Post</button>
<!-- like button -->
<button id="likeBtn" class="btn">
<img id="likeImg" src="./images/heart-outline.png" alt="like" style="width: 20px;">
</button>
<span id="likeCount">0</span>
</div>
</div>
<!-- Post Content -->
<div id="postContent" class="mt-4">
<p>Loading Content...</p>
</div>
</div>
</div>
</section>
<!-- Comment Section -->
<section id="comment-section" class="container my-4">
<div class="bg-light-brown p-4">
<h3>Comments:</h3>
<div class="d-flex">
<input type="text" id="commentInput" class="form-control" placeholder="Add a comment...">
<button id="postCommentBtn" class="btn btn-sm ms-1" type="submit">
Post
</button>
</div>
<div id="comments">
<ul id="commentsList" class="list-unstyled">
</ul>
</div>
</div>
</section>
</div>
<!-- Right Column - Sidebar -->
<div id="post-sidebar" class="col-md-4">
<div class="bg-blue p-4">
<!-- About Me -->
<div class="mb-4">
<h4 id="sidebarAuthor">About...</h4>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc faucibus venenatis sem, a
elementum eros vehicula at. Etiam quis mauris vitae libero consequat posuere eget in
urna. Integer vel volutpat leo.
</p>
</div>
<!-- Contact Info -->
<div class="mb-4">
<h4>Contact Info</h4>
<ul class="list-unstyled">
<li>Email: <a href="mailto:[email protected]">[email protected]</a></li>
</ul>
</div>
<!-- Other Recent Posts -->
<div>
<h4>Other Recent Posts</h4>
<ul class="list-unstyled">
<li><a href="#">Post Title 1</a></li>
<li><a href="#">Post Title 2</a></li>
<li><a href="#">Post Title 3</a></li>
<li><a href="#">Post Title 4</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</main>
<!-- footer -->
<footer></footer>
<!-- javascript -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="module">
import { initializePosts, getPostByID } from './scripts/blogData.js';
// function to initialize likes
async function initializeLikes() {
// get ID from URL
const urlParams = new URLSearchParams(window.location.search);
const postId = urlParams.get('id');
if (!postId) {
console.error("Error: Post ID is missing from the URL. Cannot manage likes.");
return;
}
// load blog data to get the current global like count
await initializePosts();
// get the current post object
const currentPost = getPostByID(postId);
if (!currentPost) {
console.error(`Post with ID ${postId} was not found.`);
return;
}
// initialize additional variables
// var. to determine if the client has liked a post
const IS_LIKED_KEY = `is_liked_${postId}`;
// var. to get likes from current post
let count = currentPost.likes || 0;
// var. check local storage to see if client has liked this post
let liked = localStorage.getItem(IS_LIKED_KEY) === 'true';
// var. for UI elements
const likeImg = document.getElementById("likeImg");
const likeCount = document.getElementById("likeCount");
const likeBtn = document.getElementById("likeBtn");
// update UI + images
likeCount.textContent = count;
likeImg.src = liked ? "./images/heart-filled.png" : "./images/heart-outline.png";
// event listener for like button click
likeBtn.addEventListener("click", async function (e) {
let apiEndpoint = '';
let action = '';
// check if the post has already been liked
if (liked) {
console.log("Post already liked by this user. Unliking post...")
apiEndpoint = `http://localhost:3000/api/unlike/${postId}`;
action = 'unliked';
} else {
apiEndpoint = `http://localhost:3000/api/like/${postId}`;
action = 'liked';
}
try {
const response = await fetch(apiEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' }
});
if (response.ok) {
const data = await response.json();
// toggle the state
liked = !liked;
// update UI with new global count
count = data.newLikeCount;
likeCount.textContent = count;
// switch the image based on current state
likeImg.src = liked ? "./images/heart-filled.png" : "./images/heart-outline.png";
// update local storage
localStorage.setItem(IS_LIKED_KEY, liked.toString());
console.log(`Post ${postId} ${action}. New like count: ${count}`);
} else {
console.error(`Server failed to ${action} the post.`);
}
} catch (error) {
console.error("Network error. Is the server running? Check console for details.", error);
}
})
}
initializeLikes();
</script>
<script>
// get the current user's data from local storage
const storedUser = localStorage.getItem('currentUser');
let currentUser = null;
if (storedUser) {
try {
currentUser = JSON.parse(storedUser);
} catch (e) {
console.error("Error parsing user data from localStorage:", e);
}
}
// get current post ID from URL
const postId = new URLSearchParams(window.location.search).get('id');
const list = $("#commentsList");
const admin = currentUser && currentUser.role === 'mod';
let comments = [];
function showComments() {
list.empty();
if (comments.length === 0) {
list.append('<li class="list-group-item text-center text-muted">No comments yet. Be the first to post!</li>');
return;
}
// render each comment
comments.forEach((comment, index) => {
const li = $(`
<li class="list-group-item d-flex justify-content-between align-items-center">
<span class="comment-text">${comment}</span>
</li>
`);
// delete comment -- admin only
if (admin === true) {
const deleteBtn = $(`
<button class="btn btn-sm btn-outline-danger delete-btn">Delete</button>
`);
deleteBtn.click(function () {
$(this).parent().slideUp(200, function () {
comments.splice(index, 1);
showComments();
});
})
li.append(deleteBtn);
}
list.append(li.hide().fadeIn(200));
});
}
// function to fetch latest comments
async function loadComments() {
try {
const cacheBuster = `?t=${new Date().getTime()}`;
const response = await fetch(`blogs.json${cacheBuster}`);
const posts = await response.json();
const currentPost = posts.find(p => p.id === postId);
if (currentPost && currentPost.comments) {
comments = currentPost.comments;
} else {
console.warn('No saved comments array found for this post. Initializing as empty.');
}
} catch (error) {
console.error('Failed to load initial comments:', error);
}
}
async function initializeComments() {
await loadComments();
showComments();
// add comment with button
$("#postCommentBtn").click(async function () {
const newComment = $("#commentInput").val().trim();
if (newComment !== "") {
try {
const response = await fetch(`http://localhost:3000/api/comment/${postId}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ comment: newComment })
});
if (response.ok) {
comments.push(newComment);
$("#commentInput").val("");
showComments();
console.log("Comment successfully posted and saved to server.");
} else {
console.error("Server failed to save the comment.", await response.json());
}
} catch (error) {
console.error("Network error while posting comment:", error);
}
}
});
// enter + esc functionality
$("#commentInput").keydown(function (e) {
if (e.key === "Enter") {
e.preventDefault();
$("#postCommentBtn").click();
} else if (e.key === "Escape") {
$(this).val("");
}
});
}
initializeComments();
</script>
<!-- javascript -->
<script type="module" src="./scripts/renderSinglePost.js"></script>
<script src="scripts/app.js"></script>
</body>
</html>