-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforum.html
More file actions
1757 lines (1505 loc) · 81.6 KB
/
forum.html
File metadata and controls
1757 lines (1505 loc) · 81.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
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HouseLearning Docs | Community Forum</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="/cookiebanner.js"></script>
<script type="module" src="https://www.houselearning.org/also.js"></script>
<script src="https://houselearning.github.io/feedback.js"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
'primary': '#4f46e5',
'secondary': '#8b5cf6',
'accent': '#a78bfa',
},
fontFamily: {
sans: ['Inter', 'sans-serif'],
}
}
}
}
</script>
<style>
/* Custom scrollbar for post list */
#posts-container::-webkit-scrollbar {
width: 8px;
}
#posts-container::-webkit-scrollbar-thumb {
background-color: #a78bfa;
border-radius: 10px;
}
#posts-container::-webkit-scrollbar-track {
background: #e5e7eb;
}
/* Style to hide modal */
.modal-hidden {
display: none;
}
/* Style for the 3-dot menu dropdown */
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none; /* Controlled by JS click handler */
position: absolute;
right: 0;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 10;
border-radius: 0.5rem;
overflow: hidden;
}
.dropdown-content button {
color: #374151;
padding: 12px 16px;
text-decoration: none;
display: block;
width: 100%;
text-align: left;
transition: background-color 0.2s;
font-size: 0.875rem;
}
.dropdown-content button:hover {
background-color: #e5e7eb;
}
/* Style for Vote Hover Popover */
.vote-popover {
position: absolute;
bottom: 100%; /* Position above the button */
left: 50%;
transform: translateX(-50%);
min-width: 250px;
max-height: 200px;
overflow-y: auto;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 0.5rem;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
padding: 1rem;
z-index: 20; /* Above dropdowns */
visibility: hidden;
opacity: 0;
transition: opacity 0.2s, visibility 0.2s;
}
.vote-button:hover .vote-popover {
visibility: visible;
opacity: 1;
}
</style>
</head>
<body class="bg-gray-50 font-sans min-h-screen">
<header class="bg-primary text-white shadow-lg">
<div class="max-w-4xl mx-auto p-4 flex justify-between items-center">
<h1 class="text-2xl font-extrabold tracking-tight">HouseLearning Docs | Forum</h1>
<div class="text-sm flex items-center">
<span class="font-semibold mr-2">Signed in as:</span>
<div id="user-menu" class="relative">
<button id="user-menu-button" class="flex items-center focus:outline-none">
<img id="user-avatar" src="https://robohash.org/guest.png?size=80x80&set=set3" alt="Guest avatar" class="w-8 h-8 rounded-full mr-2 bg-white/30 object-cover">
<span id="user-info" class="font-mono text-xs bg-primary/80 p-1 rounded-md">Guest</span>
</button>
<div id="user-menu-dropdown" class="hidden absolute right-0 mt-2 w-44 bg-white text-gray-800 rounded shadow-lg z-50">
</div>
</div>
<button id="sign-out-button" class="ml-4 px-3 py-1 bg-red-500 hover:bg-red-600 rounded-lg text-white font-medium text-sm transition duration-200 hidden">Sign Out</button>
</div>
</div>
</header>
<main class="max-w-4xl mx-auto p-4">
<section id="post-section" class="bg-white p-6 rounded-xl shadow-lg mb-8 border-t-4 border-accent hidden">
<h2 class="text-xl font-bold text-gray-800 mb-4">Create New Post</h2>
<form id="post-form">
<input type="text" id="post-title" required placeholder="Title (Max 50 characters)" maxlength="50"
class="w-full p-3 mb-3 border border-gray-300 rounded-lg focus:ring-secondary focus:border-secondary transition duration-150 shadow-sm">
<div class="mb-3">
<select id="post-tag" required
class="w-full p-3 border border-gray-300 rounded-lg focus:ring-secondary focus:border-secondary transition duration-150 shadow-sm bg-white appearance-none">
<option value="" disabled selected>Select a Tag *</option>
</select>
</div>
<textarea id="post-content" required placeholder="What's on your mind? (Max 500 characters)" maxlength="500" rows="4"
class="w-full p-3 mb-4 border border-gray-300 rounded-lg focus:ring-secondary focus:border-secondary transition duration-150 shadow-sm resize-none"></textarea>
<button type="submit" id="submit-button"
class="w-full bg-secondary hover:bg-accent text-white font-bold py-3 rounded-lg transition duration-300 shadow-md">
<span id="submit-text">Submit Post</span>
</button>
</form>
</section>
<section id="auth-cta" class="bg-accent/10 p-10 rounded-xl shadow-lg mb-8 text-center hidden">
<h2 class="text-2xl font-bold text-gray-800 mb-4">Join the Discussion!</h2>
<p class="text-gray-600 mb-6">You must sign in or create an account to post content or view comments.</p>
<button id="open-auth-modal" class="bg-secondary hover:bg-accent text-white font-bold py-3 px-6 rounded-lg transition duration-300 shadow-md">
Sign In / Sign Up
</button>
</section>
<section class="mb-8">
<h2 class="text-2xl font-bold text-gray-800 mb-4">Recent Discussions</h2>
<div class="flex flex-col sm:flex-row gap-3 mb-6">
<div class="flex w-full">
<input type="text" id="search-bar" placeholder="Search by title or content..."
class="flex-grow p-3 border border-gray-300 rounded-l-lg focus:ring-primary focus:border-primary transition shadow-sm">
<button id="search-button" class="px-4 bg-primary hover:bg-secondary text-white rounded-r-lg ml-2">Search</button>
</div>
<select id="tag-filter"
class="p-3 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary transition shadow-sm bg-white appearance-none w-full sm:w-48">
<option value="All">Filter by Tag (All)</option>
</select>
</div>
<div id="loading-indicator" class="text-center text-gray-500 p-8">
<div class="animate-spin inline-block w-8 h-8 border-4 border-primary border-t-transparent rounded-full"></div>
<p class="mt-2">Loading posts...</p>
</div>
<div id="posts-container" class="space-y-6 max-h-[70vh] overflow-y-auto">
</div>
<section id="thread-view" class="hidden fixed inset-0 z-50 bg-gray-100 overflow-auto p-6">
<div class="max-w-4xl mx-auto">
<div id="thread-controls" class="sticky top-4 bg-transparent z-50 flex items-center justify-between mb-4">
<button id="thread-back" class="px-3 py-1 bg-white/90 border rounded-md text-sm shadow-sm" aria-label="Back to list">← Back</button>
</div>
<div id="thread-content" class="space-y-6">
</div>
</div>
</section>
<section id="profile-view" class="hidden fixed inset-0 z-60 bg-white overflow-auto p-6">
<div class="max-w-4xl mx-auto">
<div id="profile-controls" class="sticky top-4 bg-transparent z-50 flex items-center justify-between mb-6">
<button id="profile-back" class="px-3 py-1 bg-white/90 border rounded-md text-sm shadow-sm" aria-label="Back to list">← Back</button>
</div>
<div id="profile-content" class="bg-white rounded-lg p-6 shadow space-y-6">
</div>
</div>
</section>
<p id="no-posts-message" class="text-center text-gray-500 italic p-8 hidden">No posts yet or no results found. Be the first to start a discussion!</p>
</section>
</main>
<div id="auth-modal" class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50 modal-hidden">
<div class="bg-white p-8 rounded-xl shadow-2xl w-full max-w-md mx-4 transform transition-all duration-300 scale-100 relative">
<button id="close-auth-modal" class="absolute top-3 right-3 text-gray-400 hover:text-gray-700 transition" onclick="if(window.closeAuthModal) window.closeAuthModal()">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6L6 18"/><path d="M6 6l12 12"/></svg>
</button>
<h3 id="auth-title" class="text-2xl font-bold text-gray-800 mb-6 text-center">Sign In</h3>
<div id="auth-error-message" class="text-red-600 bg-red-100 p-3 rounded-lg mb-4 hidden"></div>
<form id="auth-form">
<input type="email" id="auth-email" required placeholder="Email Address"
class="w-full p-3 mb-3 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary transition duration-150 shadow-sm">
<input type="password" id="auth-password" required placeholder="Password (min 6 characters)"
class="w-full p-3 mb-4 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary transition duration-150 shadow-sm">
<button type="submit" id="auth-submit-button"
class="w-full bg-primary hover:bg-secondary text-white font-bold py-3 rounded-lg transition duration-300 shadow-md">
<span id="auth-submit-text">Sign In</span>
</button>
</form>
<p class="text-center mt-6 text-sm">
<button id="toggle-auth-mode" class="text-primary hover:text-secondary font-medium transition duration-150">
Need an account? Sign Up
</button>
</p>
</div>
</div>
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-app.js";
import { getAuth, onAuthStateChanged, signOut, createUserWithEmailAndPassword, signInWithEmailAndPassword, setPersistence, browserLocalPersistence } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-auth.js";
// Added arrayUnion and arrayRemove for the new follow feature
// Corrected Import
import { getFirestore, collection, addDoc, onSnapshot, query, orderBy, Timestamp, increment, deleteDoc, updateDoc, doc, getDoc, getDocs, setDoc, setLogLevel, where, limit, arrayUnion, arrayRemove } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-firestore.js";
// --- CONSTANTS AND CONFIGURATION ---
const TAGS = ['Q&A', 'Bug', 'New Feature', 'Docs Issue', 'Comment', 'General'];
const TAG_COLORS = {
'Q&A': 'bg-blue-500',
'Bug': 'bg-red-500',
'New Feature': 'bg-green-500',
'Docs Issue': 'bg-yellow-500',
'Comment': 'bg-purple-500',
'General': 'bg-gray-500'
};
const defaultFirebaseConfig = {
apiKey: "AIzaSyDoXSwni65CuY1_32ZE8B1nwfQO_3VNpTw",
authDomain: "contract-center-llc-10.firebaseapp.com",
projectId: "contract-center-llc-10",
storageBucket: "contract-center-llc-10.firebasestorage.app",
messagingSenderId: "323221512767",
appId: "1:323221512767:web:6421260f875997dbf64e8a",
};
// CRITICAL: Ensure you use the global variables if defined by the framework
const firebaseConfig = JSON.parse(typeof __firebase_config !== 'undefined' ? __firebase_config : JSON.stringify(defaultFirebaseConfig));
const appId = typeof __app_id !== 'undefined' ? __app_id : 'default-app-id';
let db, auth, userId = null;
let userEmail = null;
let isSignInMode = true;
let authCheckTimeout; // Variable to hold the 5-second timeout ID
// STATE FOR SEARCH AND FILTERING
let currentSearchTerm = '';
let currentTagFilter = 'All';
// Caches for votes to power the hover popovers
// Structure: postId: { upvotes: [{email, time}], downvotes: [...] }
const voteCache = {};
// Structure: postId: { userVote: 1, -1, or 0 }
const userVoteState = {};
// Structure: userId: true/false for if the current user is following them
const followingState = {};
// --- DOM Elements ---
const postsContainer = document.getElementById('posts-container');
const form = document.getElementById('post-form');
const submitButton = document.getElementById('submit-button');
const submitText = document.getElementById('submit-text');
const loadingIndicator = document.getElementById('loading-indicator');
const noPostsMessage = document.getElementById('no-posts-message');
const postSection = document.getElementById('post-section');
const authCta = document.getElementById('auth-cta');
const userInfoSpan = document.getElementById('user-info');
const signOutButton = document.getElementById('sign-out-button');
const postTagSelect = document.getElementById('post-tag');
const tagFilterSelect = document.getElementById('tag-filter');
const searchBar = document.getElementById('search-bar');
const searchButton = document.getElementById('search-button');
// Modal Elements
const authModal = document.getElementById('auth-modal');
const authForm = document.getElementById('auth-form');
const authTitle = document.getElementById('auth-title');
const authSubmitButton = document.getElementById('auth-submit-button');
const authSubmitText = document.getElementById('auth-submit-text');
const authErrorMessage = document.getElementById('auth-error-message');
const toggleAuthModeButton = document.getElementById('toggle-auth-mode');
const openAuthModalButton = document.getElementById('open-auth-modal');
const authEmailInput = document.getElementById('auth-email');
const authPasswordInput = document.getElementById('auth-password');
const closeAuthModalButton = document.getElementById('close-auth-modal');
// New: avatar / user menu refs
const userMenuButton = document.getElementById('user-menu-button');
const userMenuDropdown = document.getElementById('user-menu-dropdown');
const userAvatar = document.getElementById('user-avatar');
// Thread View Refs
const threadView = document.getElementById('thread-view');
const threadContent = document.getElementById('thread-content');
const threadBackBtn = document.getElementById('thread-back');
// Profile View Refs
const profileView = document.getElementById('profile-view');
const profileContent = document.getElementById('profile-content');
const profileBackBtn = document.getElementById('profile-back');
// --- FIREBASE PATHS & HELPERS ---
const getPostRef = (postId) => doc(db, `artifacts/${appId}/public/data/forum_posts`, postId);
const getCommentsRef = (postId) => collection(db, `artifacts/${appId}/public/data/forum_posts/${postId}/comments`);
// New: Vote collection and doc reference
const getVotesRef = (postId) => collection(db, `artifacts/${appId}/public/data/forum_posts/${postId}/votes`);
const getVoteDocRef = (postId, userId) => doc(db, `artifacts/${appId}/public/data/forum_posts/${postId}/votes`, userId);
// Optional user profiles collection (if you store profile data)
const getUserRef = (userId) => doc(db, `artifacts/${appId}/public/data/user_profiles`, userId);
// --- UTILITY FUNCTIONS ---
function formatTimestamp(timestamp) {
if (timestamp && timestamp.toDate) {
return timestamp.toDate().toLocaleString('en-US', {
year: 'numeric', month: 'short', day: 'numeric',
hour: '2-digit', minute: '2-digit'
});
}
return 'Just now';
}
function showTemporaryMessage(message, type) {
const tempMsg = document.createElement('div');
tempMsg.textContent = message;
tempMsg.className = `fixed bottom-5 right-5 p-4 rounded-lg shadow-xl text-white font-semibold transition-opacity duration-300 z-50 ${type === 'success' ? 'bg-green-500' : 'bg-red-500'}`;
document.body.appendChild(tempMsg);
setTimeout(() => {
tempMsg.style.opacity = '0';
tempMsg.addEventListener('transitionend', () => tempMsg.remove());
}, 3000);
}
function populateTagDropdowns() {
const createOption = (tag) => `<option value="${tag}">${tag}</option>`;
postTagSelect.insertAdjacentHTML('beforeend', TAGS.map(createOption).join(''));
tagFilterSelect.insertAdjacentHTML('beforeend', TAGS.map(createOption).join(''));
}
function getDisplayName(email) {
return email ? email.split('@')[0] : 'UnknownUser';
}
// Escape HTML for profile fields
function escapeHtml(text) {
if (typeof text !== 'string') return text;
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
}
// --- FOLLOW LOGIC ---
/**
* Handles the follow/unfollow action.
* @param {string} profileUserId - The ID of the user being followed/unfollowed.
* @param {boolean} isCurrentlyFollowing - Current following state.
* @param {string} profileEmail - The email of the user (for fallback/display).
*/
/**
* Handles the follow/unfollow action between the current user and a target user.
* Matches the "Artifact User Profile" security rules.
*/
async function handleFollow(profileUserId, isCurrentlyFollowing) {
if (!userId) {
showTemporaryMessage("You must sign in to follow a user.", 'error');
return;
}
if (userId === profileUserId) {
showTemporaryMessage("You cannot follow yourself.", 'error');
return;
}
const currentUserProfileRef = getUserRef(userId);
const targetUserProfileRef = getUserRef(profileUserId);
try {
if (isCurrentlyFollowing) {
// --- UNFOLLOW ---
// Update YOUR profile (Owner rule applies: can update following list)
await updateDoc(currentUserProfileRef, {
following: arrayRemove(profileUserId),
followingCount: increment(-1)
});
// Update TARGET profile (Non-Owner rule: MUST ONLY contain followersCount)
await setDoc(targetUserProfileRef, {
followersCount: increment(-1)
}, { merge: true });
} else {
// --- FOLLOW ---
// Update YOUR profile
await updateDoc(currentUserProfileRef, {
following: arrayUnion(profileUserId),
followingCount: increment(1)
});
// Update TARGET profile (Strict: No extra fields allowed)
await setDoc(targetUserProfileRef, {
followersCount: increment(1)
}, { merge: true });
}
showTemporaryMessage(isCurrentlyFollowing ? "Unfollowed." : "Following!", 'success');
openProfile(profileUserId, userEmail); // Refresh UI
} catch (error) {
console.error("Follow error:", error);
// This triggers if you send fields other than 'followersCount' to the target
showTemporaryMessage(`Permission Denied: Ensure no extra fields are being sent.`, 'error');
}
}
// Expose the function globally for the HTML buttons
window.handleFollow = handleFollow;
// --- VOTING LOGIC ---
/**
* Sets up a real-time listener for a post's votes to update the count and user list.
* Caches results in voteCache and updates the UI on change.
*/
function loadPostVotes(postId) {
if (!db) return;
const votesRef = getVotesRef(postId);
const q = query(votesRef, orderBy("timestamp", "desc"));
onSnapshot(q, (snapshot) => {
let upvotes = [];
let downvotes = [];
let currentVote = 0; // The logged-in user's vote (1, -1, or 0)
snapshot.forEach((doc) => {
const vote = doc.data();
const voteUserId = doc.id;
const voteData = {
userId: voteUserId,
userEmail: vote.userEmail,
displayName: getDisplayName(vote.userEmail),
timestamp: vote.timestamp
};
// NOTE: The votes collection stores the *user's* vote type (1 or -1).
if (vote.type === 1) {
upvotes.push(voteData);
} else if (vote.type === -1) {
downvotes.push(voteData);
}
if (userId && voteUserId === userId) {
currentVote = vote.type;
}
});
// Update cache
voteCache[postId] = { upvotes, downvotes };
userVoteState[postId] = currentVote;
// Update UI elements for the specific post
updateVoteUI(postId, upvotes.length, downvotes.length, currentVote, true); // true for post list
updateVoteUI(postId, upvotes.length, downvotes.length, currentVote, false); // false for thread view
}, (error) => {
console.error("Error listening to votes for post", postId, ":", error);
});
}
/**
* Updates the vote count and button colors for a specific post element.
* @param {string} postId
* @param {number} upCount
* @param {number} downCount
* @param {number} userVote
* @param {boolean} isPostList - true if updating the main post list element, false for the thread view.
*/
function updateVoteUI(postId, upCount, downCount, userVote, isPostList) {
const prefix = isPostList ? '' : 'thread-';
const voteCountEl = document.getElementById(`${prefix}vote-count-${postId}`);
const upBtn = document.getElementById(`${prefix}upvote-btn-${postId}`);
const downBtn = document.getElementById(`${prefix}downvote-btn-${postId}`);
if (voteCountEl) {
voteCountEl.textContent = upCount - downCount;
}
if (upBtn) {
upBtn.classList.remove('text-green-500', 'text-gray-400', 'text-primary'); // Remove old primary color too
upBtn.classList.add(userVote === 1 ? 'text-green-500' : 'text-gray-400');
// Update the count displayed next to the icon (if element exists)
const upCountEl = upBtn.querySelector('.up-count');
if (upCountEl) upCountEl.textContent = upCount;
}
if (downBtn) {
downBtn.classList.remove('text-red-500', 'text-gray-400', 'text-primary'); // Remove old primary color too
downBtn.classList.add(userVote === -1 ? 'text-red-500' : 'text-gray-400');
// Update the count displayed next to the icon (if element exists)
const downCountEl = downBtn.querySelector('.down-count');
if (downCountEl) downCountEl.textContent = downCount;
}
}
/**
* Handles the click on an upvote or downvote button.
* @param {string} postId - The ID of the post.
* @param {number} newVoteType - 1 for upvote, -1 for downvote.
*/
/**
* Handles the follow/unfollow action between the current user and a target user.
* This is a transactional operation that requires two writes.
*/
/*
async function handleFollow(profileUserId, isCurrentlyFollowing) {
if (!userId) {
showTemporaryMessage("You must sign in to follow a user.", 'error');
return;
}
if (userId === profileUserId) {
showTemporaryMessage("You cannot follow yourself.", 'error');
return;
}
const currentUserProfileRef = getUserRef(userId);
const targetUserProfileRef = getUserRef(profileUserId);
try {
if (isCurrentlyFollowing) {
// --- UNFOLLOW ---
// Write 1: Update current user's profile (Owner rule applies)
await updateDoc(currentUserProfileRef, {
following: arrayRemove(profileUserId),
followingCount: increment(-1)
});
// Write 2: Update target user's profile (Non-Owner rule applies)
// CRITICAL FIX: Use setDoc with merge: true to create the document if missing.
await setDoc(targetUserProfileRef, {
followersCount: increment(-1)
}, { merge: true });
showTemporaryMessage("Unfollowed user.", 'success');
} else {
// --- FOLLOW ---
// Write 1: Update current user's profile (Owner rule applies)
await updateDoc(currentUserProfileRef, {
following: arrayUnion(profileUserId),
followingCount: increment(1)
});
// Write 2: Update target user's profile (Non-Owner rule applies)
// CRITICAL FIX: Use setDoc with merge: true to create the document if missing.
await setDoc(targetUserProfileRef, {
followersCount: increment(1)
}, { merge: true });
showTemporaryMessage("Following user!", 'success');
}
// Re-open the profile view to reflect the immediate change (optional but good UX)
openProfile(profileUserId, userEmail);
} catch (error) {
console.error("Error following/unfollowing:", error);
showTemporaryMessage(`Failed to update follow status: ${error.message}`, 'error');
}
}
*/
// Expose the new function globally
window.handleFollow = handleFollow;
async function handleVote(postId, newVoteType) {
if (!userId) {
showTemporaryMessage("You must sign in to vote.", 'error');
return;
}
const currentVote = userVoteState[postId] || 0;
const voteRef = getVoteDocRef(postId, userId);
// Determine the actual operation
if (currentVote === newVoteType) {
// User is unvoting (e.g., clicking upvote when already upvoted)
try {
await deleteDoc(voteRef);
// Update main post's voteCount field
await updateDoc(getPostRef(postId), {
voteCount: increment(newVoteType * -1)
});
showTemporaryMessage("Vote removed.", 'success');
} catch (error) {
console.error("Error unvoting:", error);
showTemporaryMessage(`Failed to remove vote: ${error.message}`, 'error');
}
} else {
// User is voting or switching vote (e.g., upvote to downvote)
const incrementValue = newVoteType - currentVote;
try {
// 1. Write the vote document (type 1 or -1)
await setDoc(voteRef, {
type: newVoteType,
timestamp: Timestamp.now(),
userEmail: userEmail,
userId: userId
});
// 2. Update the main post's voteCount field
// currentVote: 0 -> newVoteType (+1 or -1)
// currentVote: 1 -> newVoteType - 1 (-2 for downvote)
// currentVote: -1 -> newVoteType + 1 (+2 for upvote)
await updateDoc(getPostRef(postId), {
voteCount: increment(incrementValue)
});
showTemporaryMessage(newVoteType === 1 ? "Upvoted!" : "Downvoted!", 'success');
} catch (error) {
console.error("Error voting:", error);
showTemporaryMessage(`Failed to vote: ${error.message}`, 'error');
}
}
}
/**
* Generates the HTML content for the hover popover.
*/
function renderVotePopoverContent(postId, isUpvote) {
const cache = voteCache[postId];
if (!cache) return `<div class="text-sm text-gray-500">Loading vote list...</div>`;
const list = isUpvote ? cache.upvotes : cache.downvotes;
const action = isUpvote ? 'upvoted' : 'downvoted';
if (list.length === 0) {
return `<div class="text-sm text-gray-500">No one ${action} yet.</div>`;
}
// Show max 25 users
const displayList = list.slice(0, 25);
const hiddenCount = list.length - displayList.length;
let html = `<div class="text-sm font-semibold mb-2">${isUpvote ? 'Upvoters' : 'Downvoters'}</div>
<ul class="space-y-1 text-xs">`;
html += displayList.map(v =>
`<li>${v.displayName}</li>`
).join('');
html += `</ul>`;
if (hiddenCount > 0) {
html += `<div class="text-xs text-gray-500 mt-2">And ${hiddenCount} more rows</div>`;
}
return html;
}
/**
* Attaches event listeners for popover creation on hover.
*/
function setupPopoverListeners(postId) {
const upBtn = document.getElementById(`upvote-btn-${postId}`);
const downBtn = document.getElementById(`downvote-btn-${postId}`);
const threadUpBtn = document.getElementById(`thread-upvote-btn-${postId}`);
const threadDownBtn = document.getElementById(`thread-downvote-btn-${postId}`);
[upBtn, threadUpBtn].forEach(btn => {
if (btn) {
btn.addEventListener('mouseenter', () => {
const popover = btn.querySelector('.vote-popover');
if (popover) popover.innerHTML = renderVotePopoverContent(postId, true);
});
}
});
[downBtn, threadDownBtn].forEach(btn => {
if (btn) {
btn.addEventListener('mouseenter', () => {
const popover = btn.querySelector('.vote-popover');
if (popover) popover.innerHTML = renderVotePopoverContent(postId, false);
});
}
});
}
// --- COMMENT LOGIC ---
function renderComment(commentData) {
const isUserComment = commentData.userId === userId;
const displayUserName = getDisplayName(commentData.userEmail);
const commentElement = document.createElement('div');
commentElement.className = 'p-3 bg-gray-100 rounded-lg text-sm mb-2';
commentElement.innerHTML = `
<div class="font-medium flex justify-between items-center mb-1">
<span class="${isUserComment ? 'text-accent' : 'text-gray-700'}">${displayUserName}</span>
<span class="text-xs text-gray-500">${formatTimestamp(commentData.timestamp)}</span>
</div>
<p class="text-gray-800 whitespace-pre-wrap">${commentData.content}</p>
`;
return commentElement;
}
function loadComments(postId, commentsContainerElement) {
if (!db || !userId) return;
const commentsRef = getCommentsRef(postId);
const q = query(commentsRef, orderBy("timestamp", "asc"));
onSnapshot(q, (snapshot) => {
commentsContainerElement.innerHTML = '';
snapshot.forEach((doc) => {
const comment = doc.data();
commentsContainerElement.appendChild(renderComment(comment));
});
}, (error) => {
console.error("Error listening to comments:", error);
});
}
function submitComment(postId, inputElement) {
return async (e) => {
e.preventDefault();
if (!userId) {
showTemporaryMessage("You must be signed in to comment.", 'error');
return;
}
const content = inputElement.value.trim();
if (!content) return;
const commentsRef = getCommentsRef(postId);
inputElement.disabled = true;
try {
await addDoc(commentsRef, {
content: content,
timestamp: Timestamp.now(),
userId: userId,
userEmail: userEmail
});
inputElement.value = '';
// Scroll to bottom of comments list in thread view
if (threadContent && threadContent.contains(inputElement)) {
const commentsList = document.getElementById('thread-comments-list');
if (commentsList) commentsList.scrollTop = commentsList.scrollHeight;
}
} catch (error) {
console.error("Error submitting comment:", error);
showTemporaryMessage(`Failed to submit comment: ${error.message}`, 'error');
} finally {
inputElement.disabled = false;
}
};
}
// --- POST MANAGEMENT (CRUD) ---
async function deletePost(postId) {
// Using a simple confirm prompt since complex modals require more code/state
if (!confirm("Are you sure you want to delete this post and all its comments?")) return;
try {
// IMPORTANT: In a production environment, you must use a Callable Cloud Function
// to recursively delete all subcollections (comments and votes) as client-side
// security rules may prevent this, and there is no simple client API for recursive delete.
// For this simple example, we only delete the post document itself.
await deleteDoc(getPostRef(postId));
showTemporaryMessage("Post deleted successfully! (Note: Comments/Votes subcollections may remain in Firestore until manually deleted or by a backend job)", 'success');
// If the deleted post was open in the thread view, close it
if (location.hash === `#post:${postId}` && window.closeThread) {
window.closeThread();
}
} catch (error) {
console.error("Error deleting post:", error);
showTemporaryMessage(`Failed to delete post: ${error.message}`, 'error');
}
}
async function toggleComments(postId, currentStatus) {
try {
await updateDoc(getPostRef(postId), {
commentsDisabled: !currentStatus
});
showTemporaryMessage(`Comments successfully ${currentStatus ? 'enabled' : 'disabled'}!`, 'success');
} catch (error) {
console.error("Error toggling comments:", error);
showTemporaryMessage(`Failed to toggle comments: ${error.message}`, 'error');
}
}
function handleMenuClick(postId, isCommentsDisabled, menuButtonElement) {
const dropdownContainer = menuButtonElement.closest('.dropdown');
if (!dropdownContainer) return;
const dropdownContent = dropdownContainer.querySelector('.dropdown-content');
if (!dropdownContent) return;
// Set up button actions dynamically, calling the now globally exposed functions
dropdownContent.innerHTML = `
<button onclick="window.deletePost('${postId}')" class="text-red-600 hover:bg-red-100">Delete Post</button>
<button onclick="window.toggleComments('${postId}', ${isCommentsDisabled})">
${isCommentsDisabled ? 'Enable Comments' : 'Disable Comments'}
</button>
`;
// Simple toggle to show/hide the menu manually on button click
dropdownContent.style.display = dropdownContent.style.display === 'block' ? 'none' : 'block';
}
// --- MAIN POST RENDERING AND LISTENING ---
function renderPost(postData, postId) {
const isUserPost = postData.userId === userId;
const displayUserName = getDisplayName(postData.userEmail);
const tagColor = TAG_COLORS[postData.tag] || TAG_COLORS['General'];
const commentsDisabled = postData.commentsDisabled || false;
// Get vote count from data, default to 0
const voteCount = postData.voteCount || 0;
// Get user's current vote state from cache for initial render
const userVote = userVoteState[postId] || 0;
const upvoteClass = userVote === 1 ? 'text-green-500' : 'text-gray-400';
const downvoteClass = userVote === -1 ? 'text-red-500' : 'text-gray-400';
const postElement = document.createElement('div');
postElement.className = 'post bg-white p-5 rounded-xl shadow-md border-t-4 border-primary/50';
// Make the title a clickable anchor that opens the thread view
postElement.innerHTML = `
<div class="flex justify-between items-start mb-3">
<div class="flex-1 min-w-0">
<h3 class="text-xl font-bold text-gray-900 truncate">
<a href="#post:${postId}" onclick="if(window.openThread){window.openThread('${postId}'); return false;}" class="hover:underline">${postData.title}</a>
</h3>
</div>
<div class="flex items-center space-x-3 ml-4">
<span class="text-xs font-semibold px-3 py-1 rounded-full text-white ${tagColor} shadow-md">${postData.tag}</span>
${isUserPost ? `
<div class="dropdown">
<button class="text-gray-500 hover:text-gray-800 p-1 rounded-full hover:bg-gray-100 transition" onclick="handleMenuClick('${postId}', ${commentsDisabled}, this)">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="1"/><circle cx="12" cy="5" r="1"/><circle cx="12" cy="19" r="1"/></svg>
</button>
<div class="dropdown-content">
</div>
</div>
` : ''}
</div>
</div>
<p class="text-gray-700 mb-4 whitespace-pre-wrap">${postData.content}</p>
<div class="flex justify-between items-center text-xs text-gray-400 border-t pt-2 mt-2">
<div class="flex items-center space-x-3">
<span class="font-bold text-base text-gray-700" id="vote-count-${postId}">${voteCount}</span>
<button id="upvote-btn-${postId}" onclick="if(window.handleVote) { window.handleVote('${postId}', 1); }" class="vote-button relative flex items-center space-x-1 p-1 rounded-lg hover:bg-gray-100 transition ${upvoteClass}" aria-label="Upvote">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19V5M5 12l7-7 7 7"/></svg>
<span class="up-count text-xs">${(voteCache[postId]?.upvotes || []).length}</span>
<div class="vote-popover">Loading...</div>
</button>
<button id="downvote-btn-${postId}" onclick="if(window.handleVote) { window.handleVote('${postId}', -1); }" class="vote-button relative flex items-center space-x-1 p-1 rounded-lg hover:bg-gray-100 transition ${downvoteClass}" aria-label="Downvote">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14M5 12l7 7 7-7"/></svg>
<span class="down-count text-xs">${(voteCache[postId]?.downvotes || []).length}</span>
<div class="vote-popover">Loading...</div>
</button>
</div>
<span class="text-right">
Posted by <a href="#" onclick="if(window.openProfile) { window.openProfile('${postData.userId || ''}', '${postData.userEmail || ''}'); return false; }" class="font-medium text-gray-600 hover:underline">${displayUserName}</a> on ${formatTimestamp(postData.timestamp)}
</span>
</div>
<div class="mt-5 pt-3 border-t border-gray-200">
<h4 class="text-lg font-semibold text-gray-800 mb-3">Comments (${commentsDisabled ? 'Disabled' : 'Open'})</h4>
<div id="comments-list-${postId}" class="comments-list space-y-2 max-h-48 overflow-y-auto pr-2">
</div>
<form id="comment-form-${postId}" class="mt-4 ${commentsDisabled || !userId ? 'hidden' : 'flex items-center space-x-2'}">
<input type="text" id="comment-input-${postId}" placeholder="Write a comment..." required
class="flex-grow p-2 border border-gray-300 rounded-lg focus:ring-accent focus:border-accent text-sm" ${commentsDisabled ? 'disabled' : ''}>
<button type="submit"
class="bg-accent hover:bg-secondary text-white font-medium py-2 px-4 rounded-lg text-sm transition" ${commentsDisabled ? 'disabled' : ''}>
Send
</button>
</form>
${!userId && !commentsDisabled ? '<p class="text-sm text-gray-500 mt-4 italic">Sign in to leave a comment.</p>' : ''}
${commentsDisabled ? '<p class="text-sm text-red-500 mt-4 italic">Commenting is currently disabled for this post.</p>' : ''}
</div>
`;
// Wire up comments
const commentsListElement = postElement.querySelector(`#comments-list-${postId}`);
if (commentsListElement && userId) {
loadComments(postId, commentsListElement);
}
const commentForm = postElement.querySelector(`#comment-form-${postId}`);
const commentInput = postElement.querySelector(`#comment-input-${postId}`);
if (commentForm && commentInput) {
commentForm.addEventListener('submit', submitComment(postId, commentInput));
}
// Wire up voting listeners
if (db) {
loadPostVotes(postId); // Starts the real-time listener
setupPopoverListeners(postId);
}
return postElement;
}
// --- POST LIST LOGIC ---
function loadPosts() {
if (!db) return;
// CRITICAL: Load votes first before rendering posts to ensure initial UI state is correct
// For efficiency, we rely on the onSnapshot inside renderPost for real-time updates,
// but loadPosts triggers the render, which needs the initial vote state.
// The real-time nature of onSnapshot handles subsequent updates.
const postsRef = collection(db, `artifacts/${appId}/public/data/forum_posts`);
let q = query(postsRef, orderBy("timestamp", "desc"));
if (currentTagFilter && currentTagFilter !== 'All') {
// Firestore composite index required: (tag, timestamp DESC)
q = query(postsRef, where('tag', '==', currentTagFilter), orderBy("timestamp", "desc"));
}
onSnapshot(q, (snapshot) => {
loadingIndicator.classList.add('hidden');
let filteredPosts = [];
// 1. Process all posts first (and trigger vote listeners for them)
snapshot.forEach((doc) => {
const post = doc.data();
const postId = doc.id;
// Apply Client-Side Text Search Filter
if (currentSearchTerm) {
const searchTermLower = currentSearchTerm.toLowerCase();
if (post.title.toLowerCase().includes(searchTermLower) || post.content.toLowerCase().includes(searchTermLower)) {
filteredPosts.push({ post, postId });
}
} else {
filteredPosts.push({ post, postId });
}
// IMPORTANT: Ensure vote listeners are attached to *all* posts initially
if (db) {
// This function will fetch initial state and set up a persistent listener
loadPostVotes(postId);
}
});
// 2. Render only the filtered posts
postsContainer.innerHTML = '';
if (filteredPosts.length === 0) {
noPostsMessage.classList.remove('hidden');
return;
}
noPostsMessage.classList.add('hidden');
filteredPosts.forEach(({ post, postId }) => {
postsContainer.appendChild(renderPost(post, postId));
});
}, (error) => {
console.error("Error listening to posts:", error);
loadingIndicator.innerHTML = `<p class="text-red-500">Error loading posts: ${error.message}</p>`;
});