-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmeme-single.html
More file actions
248 lines (193 loc) · 9.1 KB
/
meme-single.html
File metadata and controls
248 lines (193 loc) · 9.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
<!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-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 memeId = params.get('id');
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/${memeId}.json`);
const meme = await res.json();
// console.log(meme)
if (!meme) return;
const commentsResponse = await fetch(`${dbURL}/comments/${memeId}.json`);
const commentsData = await commentsResponse.json();
const allComments = Object.entries(commentsData || {}).map(([id, val]) => ({ id, ...val }));
const timeAgoText = meme.createdAt ? timeAgo(meme.createdAt) : "Just now";
const tagsHTML = (meme.tags || []).map(tag => `<span>#${tag}</span>`).join('');
const voteCount = (meme.upvoteCount || 0) - (meme.downvoteCount || 0);
const userRes = await getDoc(doc(db, "users", meme.UID))
const user = userRes.data()
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">${meme.title}</h3>
<img src="${meme.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 ${meme.upvotedBy?.[currentUser.uid] ? 'active' : ''}"></i></span>
<span>${meme.upvoteCount}</span>
<span class="downvote"><i class="fa-solid fa-down-long ${meme.downvotedBy?.[currentUser.uid] ? 'active' : ''}"></i></span>
<span>${meme.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(meme, "upvote", card));
card.querySelector(".downvote").addEventListener("click", () => voteHandler(meme, "downvote", card));
// memeWrap.appendChild('afterbegin', card);
// memeWrap.insertAdjacentHTML('afterbegin', card.innerHTML);
memeWrap.prepend(card);
}
// 🗨️ Load comments using fetch
async function loadComments() {
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();
}
// ✍️ Post new comment
postBtn.addEventListener('click', async () => {
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>