-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweekly-winner.html
More file actions
275 lines (214 loc) · 10.2 KB
/
weekly-winner.html
File metadata and controls
275 lines (214 loc) · 10.2 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>memeHUB - Top meme collection</title>
<link rel="stylesheet" href="./css/main.css">
</head>
<body>
<div id="header" style="position: sticky;top: 0;z-index: 9999;"></div>
<main class="main-layout">
<div id="left-sidebar"></div>
<div id="main-content">
<!-- meme feed -->
<section class="">
<div class="meme-head">
<h3>Top meme of the week</h3>
</div>
<div class="meme-wrap">
</div>
<div class="meme-comment-form mb-1">
<textarea class="form-control" rows="5" placeholder="write comment here"></textarea>
<button class="primary-btn btn-sm">Post comment</button>
</div>
<div class="meme-comments-wrap"></div>
</section>
<!-- meme feed end -->
</div>
<div id="right-sidebar"></div>
</main>
<script type="module" src="./js/main.js"></script>
<script type="module">
import { auth, database, onAuthStateChanged, getDoc, doc, db } from "./js/firebase-init.js";
// const params = new URLSearchParams(window.location.search);
const memeWrap = document.querySelector('.meme-wrap');
const commentBox = document.querySelector('.meme-comment-form textarea');
const postBtn = document.querySelector('.meme-comment-form button');
const commentsWrap = document.querySelector('.meme-comments-wrap');
// const currentUser = JSON.parse(localStorage.getItem("meme-hub-user") || "{}");
const dbURL = "https://memehub-4e730-default-rtdb.asia-southeast1.firebasedatabase.app";
// 👤 Load user and data
onAuthStateChanged(auth, (user) => {
if (!user) {
postBtn.attr('disabled', true)
}
});
// 🖼️ Load Meme using fetch
async function loadMeme() {
const res = await fetch(`${dbURL}/memes.json`);
const memes = await res.json();
if (!memes) return;
const memesArray = Object.entries(memes).map(([id, meme]) => ({
...meme,
id,
voteCount: (meme.upvoteCount || 0) - (meme.downvoteCount || 0)
}));
const now = Date.now();
const oneDayAgo = now - (7 * 24 * 60 * 60 * 1000);
const recentMemes = memesArray.filter(m => m.createdAt && m.createdAt >= oneDayAgo);
if (recentMemes.length === 0) {
memeWrap.innerHTML = `<p>No memes posted in the last 24 hours.</p>`;
return;
}
// Sort by vote count descending
const topMeme = recentMemes.sort((a, b) => b.voteCount - a.voteCount)[0];
setMemeId(topMeme.id)
const userRes = await getDoc(doc(db, "users", topMeme.UID));
const user = userRes.exists() ? userRes.data() : {};
const commentsResponse = await fetch(`${dbURL}/comments/${topMeme.id}.json`);
const commentsData = await commentsResponse.json();
const allComments = Object.entries(commentsData || {}).map(([id, val]) => ({ id, ...val }));
const timeAgoText = topMeme.createdAt ? timeAgo(topMeme.createdAt) : "Just now";
const tagsHTML = (topMeme.tags || []).map(tag => `<span>#${tag}</span>`).join('');
const card = document.createElement("div");
card.className = "meme-card";
card.innerHTML = `
<div class="meme-head">
<div class="m-head-left">
<span><img src="${user.avatar || 'https://t4.ftcdn.net/jpg/12/44/29/93/240_F_1244299369_Jixobpdd2rDzg1B6DZw4tRmSa02OY0Qh.jpg'}" alt=""></span>
<span>${user.userName || 'Anonymous'}</span>
<span>${timeAgoText}</span>
</div>
<div class="m-head-right"><span><i class="fa-solid fa-flag"></i></span></div>
</div>
<div class="meme-media">
<h3 class="mb-1">${topMeme.title}</h3>
<img src="${topMeme.image}" alt="">
</div>
<div class="meme-tags">${tagsHTML}</div>
<div class="meme-actions">
<div class="meme-votes">
<span class="upvote"><i class="fa-solid fa-up-long ${topMeme.upvotedBy?.[currentUser.uid] ? 'active' : ''}"></i></span>
<span>${topMeme.upvoteCount}</span>
<span class="downvote"><i class="fa-solid fa-down-long ${topMeme.downvotedBy?.[currentUser.uid] ? 'active' : ''}"></i></span>
<span>${topMeme.downvoteCount}</span>
</div>
<div class="meme-comments">
<span><i class="fa-solid fa-comments"></i></span>
<span id="comment-count">${allComments.length}</span>
</div>
</div>
`;
// Add voting listeners
card.querySelector(".upvote").addEventListener("click", () => voteHandler(topMeme, "upvote", card));
card.querySelector(".downvote").addEventListener("click", () => voteHandler(topMeme, "downvote", card));
// memeWrap.appendChild('afterbegin', card);
// memeWrap.insertAdjacentHTML('afterbegin', card.innerHTML);
memeWrap.prepend(card);
}
// 🗨️ Load comments using fetch
async function loadComments() {
const memeId = localStorage.getItem("topmemeId")?localStorage.getItem("topmemeId"):"";
const res = await fetch(`${dbURL}/comments/${memeId}.json`);
const data = await res.json();
commentsWrap.innerHTML = '';
let count = 0;
if (!data) return;
for (const [id, comment] of Object.entries(data)) {
commentsWrap.innerHTML += renderComment(id, comment);
count++;
}
const countEl = document.getElementById('comment-count');
if (countEl) countEl.textContent = count;
setupEditDeleteListeners();
}
function setMemeId(memeId){
localStorage.setItem("topmemeId",memeId)
loadComments()
}
// ✍️ Post new comment
postBtn.addEventListener('click', async () => {
const memeId = localStorage.getItem("topmemeId")?localStorage.getItem("topmemeId"):"";
const text = commentBox.value.trim();
if (!text || !currentUser) return;
const userRes = await getDoc(doc(db, "users", currentUser.uid))
const user = userRes.data()
const comment = {
userId: currentUser.uid,
username: user.userName || "Anonymous",
avatar: user.avatar || "https://t4.ftcdn.net/jpg/12/44/29/93/240_F_1244299369_Jixobpdd2rDzg1B6DZw4tRmSa02OY0Qh.jpg",
text,
createdAt: Date.now()
};
const res = await fetch(`${dbURL}/comments/${memeId}.json`, {
method: 'POST',
body: JSON.stringify(comment),
headers: { 'Content-Type': 'application/json' }
});
if (res.ok) commentBox.value = '';
loadComments(); // Refresh
});
function renderComment(id, comment) {
const isOwner = currentUser && comment.userId === currentUser.uid;
return `
<div class="meme-user-comment" data-id="${id}">
<div class="comment-user">
<span><img src="${comment.avatar}" alt=""></span>
<span>${comment.username}</span>
<span>${timeAgo(comment.createdAt)}</span>
</div>
<div class="comment-text">${comment.text}</div>
${isOwner ? `
<div style="display:flex; gap:0.5rem; margin-top:0.5rem;">
<button class="edit-comment primary-btn btn-sm">Edit</button>
<button class="delete-comment danger-btn btn-sm">Delete</button>
</div>
` : ''}
</div>
`;
}
// 📝 Edit & 🗑 Delete
function setupEditDeleteListeners() {
document.querySelectorAll('.edit-comment').forEach(btn => {
btn.addEventListener('click', async () => {
const parent = btn.closest('.meme-user-comment');
const id = parent.dataset.id;
const textDiv = parent.querySelector('.comment-text');
const newText = prompt("Edit your comment:", textDiv.textContent);
if (newText && newText.trim() !== "") {
await fetch(`${dbURL}/comments/${memeId}/${id}.json`, {
method: 'PATCH',
body: JSON.stringify({ text: newText.trim() }),
headers: { 'Content-Type': 'application/json' }
});
loadComments();
}
});
});
document.querySelectorAll('.delete-comment').forEach(btn => {
btn.addEventListener('click', async () => {
const parent = btn.closest('.meme-user-comment');
const id = parent.dataset.id;
if (confirm("Are you sure you want to delete this comment?")) {
await fetch(`${dbURL}/comments/${memeId}/${id}.json`, {
method: 'DELETE'
});
loadComments();
}
});
});
}
function timeAgo(timestamp) {
const diff = Date.now() - timestamp;
const mins = Math.floor(diff / 60000);
if (mins < 1) return "just now";
if (mins < 60) return `${mins} min ago`;
const hrs = Math.floor(mins / 60);
return `${hrs} hr${hrs > 1 ? 's' : ''} ago`;
}
loadMeme();
// loadComments();
</script>
</body>
</html>