-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1301 lines (1168 loc) · 45 KB
/
index.html
File metadata and controls
1301 lines (1168 loc) · 45 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
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#111827">
<title>TempChats - Secure Temporary Chat Rooms</title>
<!-- Load Firebase SDKs before React -->
<script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-firestore-compat.js"></script>
<!-- Initialize Firebase -->
<script>
const firebaseConfig = {
apiKey: "APIKEY",
authDomain: "AUTHDOMAIN",
databaseURL: "DATABASEURL",
projectId: "PROJECTID",
storageBucket: "STORAGEBUCKET",
messagingSenderId: "MESSAGINGSENDERID",
appId: "APPID",
measurementId: "MEASUREMENTID"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
// Add this function after Firebase initialization
function setupExpirationCleanup() {
// Check for expired rooms every minute
setInterval(async () => {
try {
const now = firebase.firestore.Timestamp.now();
// Get expired rooms
const expiredRoomsSnapshot = await db.collection('rooms')
.where('expires_at', '<=', now)
.get();
if (expiredRoomsSnapshot.empty) return;
const batch = db.batch();
const expiredRoomIds = [];
// Collect expired room IDs and prepare room deletions
expiredRoomsSnapshot.forEach(doc => {
expiredRoomIds.push(doc.id);
batch.delete(doc.ref);
});
// Get and delete all messages from expired rooms
const messagesSnapshot = await db.collection('messages')
.where('room_id', 'in', expiredRoomIds)
.get();
messagesSnapshot.forEach(doc => {
batch.delete(doc.ref);
});
// Execute all deletions
await batch.commit();
console.log(`Cleaned up ${expiredRoomsSnapshot.size} expired rooms and their messages`);
} catch (error) {
console.error('Error cleaning up expired rooms:', error);
}
}, 60000); // Run every minute
}
// Call the setup function after Firebase initialization
setupExpirationCleanup();
</script>
<!-- Load React after Firebase -->
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="styles.css">
<!-- Add Material Icons -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div id="root"></div>
<!-- Add Toast Container -->
<div id="toast-container" class="fixed bottom-4 right-4 z-50"></div>
<script type="text/babel">
// Login Component
function Login({ onLogin }) {
const [username, setUsername] = React.useState('');
const [isChecking, setIsChecking] = React.useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
if (!username.trim() || isChecking) return;
const cleanUsername = username.trim();
if (cleanUsername.length < 3) {
window.showToast('Username must be at least 3 characters', 'error');
return;
}
setIsChecking(true);
try {
// First check if user exists in localStorage
const localUser = localStorage.getItem('userDetails');
if (localUser) {
const userData = JSON.parse(localUser);
if (userData.username === cleanUsername) {
onLogin(cleanUsername, userData.userId);
return;
}
}
// Check database only for new usernames
const snapshot = await db.collection('users')
.where('username', '==', cleanUsername)
.get();
if (!snapshot.empty) {
window.showToast('Username already taken', 'error');
return;
}
// Create new user document
const userRef = await db.collection('users').add({
username: cleanUsername,
created_at: firebase.firestore.FieldValue.serverTimestamp()
});
// Store user details locally
const userDetails = {
username: cleanUsername,
userId: userRef.id,
loginTime: new Date().toISOString()
};
localStorage.setItem('userDetails', JSON.stringify(userDetails));
onLogin(cleanUsername, userRef.id);
window.showToast('Welcome to TempChats!', 'success');
} catch (error) {
console.error('Error during login:', error);
window.showToast('Error during login. Please try again.', 'error');
} finally {
setIsChecking(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gray-900">
<div className="max-w-md w-full space-y-8 p-8 dark-card rounded-lg shadow">
<h2 className="text-3xl font-bold text-center text-gray-100">Welcome to TempChats</h2>
<form onSubmit={handleSubmit} className="mt-8 space-y-6">
<div>
<label htmlFor="username" className="block text-sm font-medium text-gray-300">
Choose a username
</label>
<input
id="username"
type="text"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
className="mt-1 dark-input block w-full rounded-md"
placeholder="Enter username"
disabled={isChecking}
/>
</div>
<button
type="submit"
disabled={isChecking}
className={`w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 ${
isChecking ? 'opacity-50 cursor-not-allowed' : ''
}`}
>
{isChecking ? (
<span className="flex items-center">
<span className="material-icons animate-spin mr-2">refresh</span>
Checking...
</span>
) : (
'Start Chatting'
)}
</button>
</form>
</div>
</div>
);
}
// Main App Component
function App() {
const [view, setView] = React.useState('login');
const [username, setUsername] = React.useState('');
const [userId, setUserId] = React.useState(null);
const [currentRoom, setCurrentRoom] = React.useState(null);
const [lastRoom, setLastRoom] = React.useState(null);
// Add login persistence check
React.useEffect(() => {
const userDetails = localStorage.getItem('userDetails');
if (userDetails) {
const { username, userId } = JSON.parse(userDetails);
setUsername(username);
setUserId(userId);
setView('landing');
}
}, []);
const handleLogin = (username, userId) => {
setUsername(username);
setUserId(userId);
setView('landing');
};
const handleLogout = async () => {
try {
if (userId) {
// Delete user's rooms
const userRooms = await db.collection('rooms')
.where('creator', '==', username)
.get();
const batch = db.batch();
userRooms.forEach(doc => {
batch.delete(doc.ref);
});
// Delete user's messages
const userMessages = await db.collection('messages')
.where('sender', '==', username)
.get();
userMessages.forEach(doc => {
batch.delete(doc.ref);
});
// Delete user document
batch.delete(db.collection('users').doc(userId));
await batch.commit();
}
// Clear local storage
localStorage.removeItem('userDetails');
setUsername('');
setUserId(null);
setCurrentRoom(null);
setLastRoom(null);
setView('login');
window.showToast('Logged out successfully', 'success');
} catch (error) {
console.error('Error during logout:', error);
window.showToast('Error during logout', 'error');
}
};
const handleCreateRoom = async (roomData) => {
try {
// Check for existing rooms with same name
const existingRooms = await db.collection('rooms')
.where('name', '==', roomData.name)
.get();
let finalName = roomData.name;
if (!existingRooms.empty) {
let counter = 1;
while (true) {
const newName = `${roomData.name} (${counter})`;
const checkName = await db.collection('rooms')
.where('name', '==', newName)
.get();
if (checkName.empty) {
finalName = newName;
break;
}
counter++;
}
}
const roomCode = Math.random().toString(36).substring(2, 8).toUpperCase();
const newRoom = {
...roomData,
name: finalName,
creator: username,
room_code: roomCode,
created_at: firebase.firestore.FieldValue.serverTimestamp(),
expires_at: firebase.firestore.Timestamp.fromDate(
new Date(Date.now() + (parseInt(roomData.duration) || 1) * 60 * 60 * 1000)
),
active_users: [username]
};
const roomRef = await db.collection('rooms').add(newRoom);
setCurrentRoom({ id: roomRef.id, ...newRoom });
setView('chat');
window.showToast('Room created successfully!', 'success');
} catch (error) {
console.error('Error creating room:', error);
window.showToast('Failed to create room: ' + error.message, 'error');
}
};
const handleLeaveRoom = () => {
setCurrentRoom(null);
setLastRoom(null);
setView('landing');
window.showToast('Left room successfully', 'success');
};
const handleJoinRoom = async (roomId) => {
try {
const roomDoc = await db.collection('rooms').doc(roomId).get();
if (!roomDoc.exists) {
window.showToast('Room not found', 'error');
return;
}
const roomData = { id: roomDoc.id, ...roomDoc.data() };
// Check if room is private and user is not creator
if (roomData.isPrivate && roomData.creator !== username) {
// Create and show modal for private room confirmation
const confirmJoin = confirm(`
Private Room Details:
Name: ${roomData.name}
Creator: ${roomData.creator}
Latest Message: ${roomData.latestMessage || 'No messages yet'}
Would you like to join this private room?
`);
if (!confirmJoin) return;
const codeInput = prompt('Please enter the room code:');
if (codeInput !== roomData.room_code) {
window.showToast('Invalid room code', 'error');
return;
}
}
setCurrentRoom(roomData);
setView('chat');
window.showToast('Joined room successfully!', 'success');
} catch (error) {
console.error('Error joining room:', error);
window.showToast('Failed to join room', 'error');
}
};
return (
<div className="min-h-screen bg-gray-900 text-gray-100">
{view === 'login' && (
<Login onLogin={handleLogin} />
)}
{view === 'landing' && (
<LandingPage
username={username}
onCreateRoom={() => setView('create')}
onJoinRoom={handleJoinRoom}
onLogout={handleLogout}
lastRoom={lastRoom}
setLastRoom={setLastRoom}
/>
)}
{view === 'create' && (
<CreateRoom
onRoomCreated={(roomData) => {
setCurrentRoom(roomData);
setView('chat');
}}
onCancel={() => setView('landing')}
username={username}
/>
)}
{view === 'chat' && currentRoom && (
<ChatRoom
room={currentRoom}
username={username}
onLeave={() => {
setCurrentRoom(null);
setView('landing');
}}
/>
)}
<PrivacyBanner />
</div>
);
}
// Landing Page Component
function LandingPage({ onCreateRoom, onJoinRoom, username, lastRoom, onLogout, setLastRoom }) {
const [joinCode, setJoinCode] = React.useState('');
const [showJoinInput, setShowJoinInput] = React.useState(false);
const [publicRooms, setPublicRooms] = React.useState([]);
const [isLoading, setIsLoading] = React.useState(true);
const [searchQuery, setSearchQuery] = React.useState('');
const unsubscribeRef = React.useRef(null);
// Add search filter function
const filteredRooms = publicRooms.filter(room =>
room.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
room.creator.toLowerCase().includes(searchQuery.toLowerCase())
);
React.useEffect(() => {
loadRooms();
return () => {
if (unsubscribeRef.current) {
unsubscribeRef.current();
}
};
}, []);
const loadRooms = async () => {
setIsLoading(true);
try {
// Unsubscribe from previous listener if exists
if (unsubscribeRef.current) {
unsubscribeRef.current();
}
// Set up real-time listener
unsubscribeRef.current = db.collection('rooms')
.where('isPrivate', '==', false)
.where('expires_at', '>', firebase.firestore.Timestamp.now())
.onSnapshot(snapshot => {
const rooms = new Map(); // Use Map to prevent duplicates
snapshot.forEach(doc => {
const room = { id: doc.id, ...doc.data() };
rooms.set(room.id, room); // Use room ID as key
});
setPublicRooms(Array.from(rooms.values()));
setIsLoading(false);
});
} catch (error) {
console.error('Error loading rooms:', error);
window.showToast('Error loading rooms', 'error');
setIsLoading(false);
}
};
const handleJoinWithCode = async (e) => {
e.preventDefault();
if (!joinCode.trim()) return;
try {
const roomSnapshot = await db.collection('rooms')
.where('room_code', '==', joinCode.trim().toUpperCase())
.get();
if (roomSnapshot.empty) {
window.showToast('Room not found', 'error');
return;
}
const roomDoc = roomSnapshot.docs[0];
const roomData = roomDoc.data();
if (roomData.expires_at.toDate() < new Date()) {
window.showToast('This room has expired', 'error');
return;
}
onJoinRoom(roomDoc.id);
setJoinCode('');
setShowJoinInput(false);
} catch (error) {
console.error('Error joining room:', error);
window.showToast('Error joining room', 'error');
}
};
return (
<div className="container mx-auto px-4 py-8">
{/* Header */}
<div className="flex justify-between items-center mb-8">
<h1 className="text-3xl font-bold text-gray-100">TempChats</h1>
<div className="flex items-center gap-4">
<p className="text-gray-300">Hello, {username}!</p>
<button
onClick={onLogout}
className="px-3 py-1 dark-surface-light rounded hover:bg-gray-700"
>
Logout
</button>
</div>
</div>
{/* Return to Room Banner */}
{lastRoom && (
<div className="bg-blue-600 text-white px-4 py-3 rounded-lg mb-6 flex justify-between items-center">
<span>You're still in "{lastRoom.name}". Return or leave permanently.</span>
<div className="flex gap-2">
<button
onClick={() => onJoinRoom(lastRoom.id)}
className="px-3 py-1 bg-blue-700 rounded hover:bg-blue-800"
>
Return
</button>
<button
onClick={handleLeaveRoom}
className="px-3 py-1 bg-red-600 rounded hover:bg-red-700"
>
Leave Room
</button>
</div>
</div>
)}
{/* Action Buttons */}
<div className="flex gap-4 mb-8">
<div className="grid grid-cols-1 md:grid-cols-2 gap-8 mb-12">
<div className="dark-card p-6 rounded-lg shadow">
<h2 className="text-xl font-semibold mb-4 text-gray-100">Create a Room</h2>
<p className="mb-4 text-gray-300">Start a new chat room with custom settings</p>
<button
onClick={() => setView('create')}
className="w-full dark-button"
>
Create Room
</button>
</div>
<div className="relative">
<button
onClick={() => setShowJoinInput(!showJoinInput)}
className="px-4 py-2 dark-surface-light hover:bg-gray-700 rounded-lg flex items-center"
>
<span className="material-icons mr-2">input</span>
Join with Code
</button>
{showJoinInput && (
<form
onSubmit={handleJoinWithCode}
className="absolute top-full mt-2 right-0 bg-gray-800 p-3 rounded-lg shadow-lg animate-fadeIn z-10"
>
<div className="flex gap-2">
<input
type="text"
value={joinCode}
onChange={(e) => setJoinCode(e.target.value)}
placeholder="Enter room code"
className="dark-input rounded px-3 py-1"
/>
<button
type="submit"
className="px-3 py-1 bg-blue-600 hover:bg-blue-700 rounded"
>
Join
</button>
</div>
</form>
)}
</div>
</div>
{/* Add search bar */}
<div className="mb-6">
<div className="relative">
<span className="absolute inset-y-0 left-0 pl-3 flex items-center">
<span className="material-icons text-gray-400">search</span>
</span>
<input
type="text"
placeholder="Search rooms by name or creator..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full pl-10 pr-4 py-2 dark-input rounded-lg"
/>
</div>
</div>
{/* Public Rooms Section */}
<div className="mt-8">
<div className="flex justify-between items-center mb-4">
<h2 className="text-xl font-semibold">Public Rooms</h2>
<button
onClick={loadRooms}
className="px-3 py-1 dark-surface-light rounded hover:bg-gray-700 flex items-center"
disabled={isLoading}
>
<span className={`material-icons mr-1 ${isLoading ? 'animate-spin' : ''}`}>
refresh
</span>
Refresh
</button>
</div>
{isLoading ? (
<div className="text-center py-8">
<span className="material-icons animate-spin text-4xl">refresh</span>
<p className="mt-2 text-gray-400">Loading rooms...</p>
</div>
) : filteredRooms.length === 0 ? (
<div className="text-center py-8 dark-card rounded-lg">
<span className="material-icons text-4xl text-gray-400">search_off</span>
<p className="mt-2 text-gray-400">No public rooms available</p>
<button
onClick={onCreateRoom}
className="mt-4 px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg"
>
Create a Room
</button>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{filteredRooms.map(room => (
<RoomCard
key={room.id}
room={room}
onJoinRoom={onJoinRoom}
username={username}
isCurrentlyIn={lastRoom?.id === room.id}
/>
))}
</div>
)}
</div>
{/* Add credits at the bottom of the landing page */}
<div className="mt-8 text-center text-gray-400 text-xs">
<p>Created by <a href="https://github.com/DaDevMikey" className="text-blue-400 hover:underline">@DaDevMikey</a></p>
<p>Visit <a href="https://nexas-development.vercel.app/" className="text-blue-400 hover:underline">Nexas Development</a></p>
</div>
</div>
</div>
);
}
// Helper function to calculate time left
function formatTimeLeft(expiryDate) {
const now = new Date();
const diff = expiryDate - now;
const minutes = Math.floor(diff / 60000);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if (days > 0) {
return `${days} day${days > 1 ? 's' : ''} left`;
} else if (hours > 0) {
return `${hours} hour${hours > 1 ? 's' : ''} left`;
} else if (minutes > 0) {
return `${minutes} minute${minutes > 1 ? 's' : ''} left`;
} else {
return 'Expiring soon';
}
}
// Toast Component
function Toast({ message, type = 'success', onClose }) {
const bgColor = {
success: 'bg-green-500',
error: 'bg-red-500',
info: 'bg-gray-500'
}[type];
const icon = {
success: 'check_circle',
error: 'error',
info: 'info'
}[type];
React.useEffect(() => {
const timer = setTimeout(onClose, 5000);
return () => clearTimeout(timer);
}, [onClose]);
return (
<div className={`${bgColor} text-white px-4 py-3 rounded-lg shadow-lg flex items-center mb-2 animate-slide-in`}>
<span className="material-icons mr-2">{icon}</span>
{message}
<button onClick={onClose} className="ml-4">
<span className="material-icons">close</span>
</button>
</div>
);
}
// Toast Manager Component
function ToastManager() {
const [toasts, setToasts] = React.useState([]);
window.showToast = (message, type = 'success') => {
const id = Date.now();
setToasts(prev => [...prev, { id, message, type }]);
};
const removeToast = (id) => {
setToasts(prev => prev.filter(toast => toast.id !== id));
};
return ReactDOM.createPortal(
<div className="fixed bottom-4 right-4 z-50">
{toasts.map(toast => (
<Toast
key={toast.id}
message={toast.message}
type={toast.type}
onClose={() => removeToast(toast.id)}
/>
))}
</div>,
document.getElementById('toast-container')
);
}
// Create Room Component
function CreateRoom({ onRoomCreated, onCancel, username }) {
const [formData, setFormData] = React.useState({
name: '',
duration: '1',
isPrivate: false,
moderation_level: 'minimal'
});
const handleSubmit = async (e) => {
e.preventDefault();
try {
await onRoomCreated(formData);
} catch (error) {
console.error('Error creating room:', error);
window.showToast('Failed to create room', 'error');
}
};
return (
<div className="container mx-auto px-4 py-8">
<div className="max-w-2xl mx-auto dark-card p-6 rounded-lg shadow">
<div className="flex justify-between items-center mb-6">
<h2 className="text-2xl font-semibold text-gray-100">Create a New Room</h2>
<button
onClick={onCancel}
className="text-gray-400 hover:text-gray-300"
>
<span className="material-icons">close</span>
</button>
</div>
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
<div className="mb-4">
<label className="block text-sm font-medium text-gray-300 mb-2">
Room Name
</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
className="dark-input w-full rounded"
required
/>
</div>
<div className="mb-4">
<label className="block text-sm font-medium text-gray-300 mb-2">
Duration
</label>
<select
value={formData.duration}
onChange={(e) => setFormData(prev => ({ ...prev, duration: e.target.value }))}
className="dark-input w-full rounded"
>
<option value="1">1 hour</option>
<option value="3">3 hours</option>
<option value="6">6 hours</option>
<option value="12">12 hours</option>
<option value="24">24 hours</option>
</select>
</div>
<div className="mb-4">
<label className="block text-sm font-medium text-gray-300 mb-2">
Content Moderation
</label>
<select
value={formData.moderation_level}
onChange={(e) => setFormData(prev => ({ ...prev, moderation_level: e.target.value }))}
className="dark-input w-full rounded"
>
<option value="minimal">Minimal (Block Racial Slurs)</option>
<option value="advanced">Advanced (Block All Slurs)</option>
</select>
</div>
<div className="mb-6">
<label className="flex items-center">
<input
type="checkbox"
checked={formData.isPrivate}
onChange={(e) => setFormData(prev => ({ ...prev, isPrivate: e.target.checked }))}
className="dark-input rounded mr-2"
/>
<span className="text-sm text-gray-300">Make room private</span>
</label>
</div>
<div className="flex gap-4 mt-6">
<button
type="button"
onClick={onCancel}
className="flex-1 px-4 py-2 dark-surface-light rounded hover:bg-gray-700"
>
Cancel
</button>
<button
type="submit"
className="flex-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded"
>
Create Room
</button>
</div>
</form>
</div>
</div>
);
}
// Chat Room Component
function ChatRoom({ room, username, onLeave }) {
const [messages, setMessages] = React.useState([]);
const [inputValue, setInputValue] = React.useState('');
const [replyTo, setReplyTo] = React.useState(null);
const messageListRef = React.useRef(null);
const [typingUsers, setTypingUsers] = React.useState(new Set());
const typingTimeoutRef = React.useRef(null);
// Add reply handling
const handleReply = (message) => {
setReplyTo(message);
// Focus input field
document.querySelector('input[type="text"]').focus();
};
const handleTyping = (e) => {
const text = e.target.value;
setInputValue(text);
// Check if typing should be triggered
if (text.length > 10 || text.split(' ').length > 2) {
// Update typing status in Firestore
updateTypingStatus(true);
// Clear existing timeout
if (typingTimeoutRef.current) {
clearTimeout(typingTimeoutRef.current);
}
// Set new timeout
typingTimeoutRef.current = setTimeout(() => {
updateTypingStatus(false);
}, 3000);
}
};
const updateTypingStatus = async (isTyping) => {
try {
const typingRef = db.collection('typing').doc(room.id);
if (isTyping) {
await typingRef.set({
[username]: firebase.firestore.FieldValue.serverTimestamp()
}, { merge: true });
} else {
await typingRef.update({
[username]: firebase.firestore.FieldValue.delete()
});
}
} catch (error) {
console.error('Error updating typing status:', error);
}
};
// Add effect to listen for typing users
React.useEffect(() => {
if (!room?.id) return;
const unsubscribe = db.collection('typing')
.doc(room.id)
.onSnapshot(doc => {
if (doc.exists) {
const data = doc.data();
const now = new Date();
const activeTypers = new Set(
Object.entries(data)
.filter(([user, timestamp]) => {
const typingTime = timestamp?.toDate();
return typingTime &&
(now - typingTime) < 3000 &&
user !== username;
})
.map(([user]) => user)
);
setTypingUsers(activeTypers);
} else {
setTypingUsers(new Set());
}
});
return () => unsubscribe();
}, [room?.id, username]);
const handleSendMessage = async (e) => {
e.preventDefault();
if (!inputValue.trim()) return;
const moderatedContent = moderateContent(inputValue.trim(), room.moderation_level);
const replyData = replyTo ? {
sender: replyTo.sender,
content: replyTo.content
} : null;
try {
// Send message
await db.collection('messages').add({
room_id: room.id,
sender: username,
content: moderatedContent,
reply_to: replyData,
created_at: firebase.firestore.FieldValue.serverTimestamp()
});
// Update room's latest message
await db.collection('rooms').doc(room.id).update({
latestMessage: `${username}: ${moderatedContent}`,
lastActivity: firebase.firestore.FieldValue.serverTimestamp()
});
// Clear input and reply after successful send
setInputValue('');
setReplyTo(null);
updateTypingStatus(false);
} catch (error) {
console.error('Error sending message:', error);
window.showToast('Error sending message', 'error');
}
};
const moderateContent = (text, level) => {
const slurs = {
minimal: [
{ pattern: /n[i1]gg[e3]r/gi, replacement: '***' },
{ pattern: /k[i1]k[e3]/gi, replacement: '***' }
],
advanced: [
{ pattern: /f[u\*]ck/gi, replacement: '***' },
{ pattern: /sh[i1]t/gi, replacement: '***' },
{ pattern: /b[i1]tch/gi, replacement: '***' },
{ pattern: /[a@]ss/gi, replacement: '***' },
{ pattern: /d[i1]ck/gi, replacement: '***' }
]
};
let moderatedText = text;
const patterns = [...(slurs.minimal || []), ...(level === 'advanced' ? slurs.advanced : [])];
patterns.forEach(({ pattern, replacement }) => {
moderatedText = moderatedText.replace(pattern, replacement);
});
return moderatedText;
};
// Load and listen to messages
React.useEffect(() => {
if (!room?.id) return;
const messageUnsubscribe = db.collection('messages')
.where('room_id', '==', room.id)
.orderBy('created_at', 'asc')
.onSnapshot(snapshot => {
const newMessages = [];
snapshot.forEach(doc => {
newMessages.push({ id: doc.id, ...doc.data() });
});
setMessages(newMessages);
});
return () => {
messageUnsubscribe();
if (typingTimeoutRef.current) {
clearTimeout(typingTimeoutRef.current);
}
updateTypingStatus(false);
};
}, [room?.id]);
if (!room) {
return <div>Loading chat room...</div>;
}
return (
<div className="h-screen flex flex-col bg-gray-900">
<div className="flex justify-between items-center p-4 border-b border-gray-700">
<div>
<h2 className="text-xl font-semibold text-gray-100">
{room.name}
<button