-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
1156 lines (970 loc) · 44.3 KB
/
main.js
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
import './src/css/style.css'
import { Header } from './src/components/Header';
import { Body } from './src/components/Body';
import { uri } from './api';
if (localStorage.getItem("loggedInUser") != "") {
document.querySelector("body").classList.add("overflow-y-hidden");
} else {
document.querySelector("body").classList.remove("overflow-y-hidden");
}
if("theme" in localStorage) {
null;
} else {
localStorage.setItem("theme", "light");
}
let secondPerson = {};
var today = new Date();
var dd = String(today.getDate()).padStart(2, "0");
var mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
var yyyy = today.getFullYear();
today = mm + "/" + dd + "/" + yyyy;
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? "pm" : "am";
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? "0" + minutes : minutes;
var strTime = hours + ":" + minutes + " " + ampm;
return strTime;
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = "";
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
const app = document.querySelector("#app");
app.insertAdjacentHTML("afterbegin", Body);
app.insertAdjacentHTML("afterbegin", Header);
//Sidebar backdrop toggle
const toggleBackdrop = () => {
const backdrop = document.querySelector(".backdrop");
if (backdrop.classList.contains("hidden")) {
backdrop.classList.remove("hidden");
} else {
backdrop.classList.add("hidden");
}
}
//Log Out Function
document.querySelector("#sidebarToggleBtn").addEventListener("click", toggleBackdrop);
document.querySelector("#sidebar").addEventListener("click", (event) => event.stopPropagation());
document.querySelector(".backdrop").addEventListener("click", toggleBackdrop);
document.querySelector("#logout").addEventListener("click", () => {
localStorage.setItem("loggedInUser", "");
console.log("Logout Successfully Done");
setTimeout(() => window.location.href = "", 1000);
})
//Fetch users
const initUsersRes = await fetch(uri + "/users");
let usersData = await initUsersRes.json();
let users = usersData;
let loggedInUser = users.filter((user) => {
if (user.uid == parseInt(localStorage.getItem("loggedInUser"))) {
return user;
}
})
loggedInUser = loggedInUser[0];
//Fetch chats
const initChatsRes = await fetch(uri + "/chats");
let chatsData = await initChatsRes.json();
let chats = chatsData;
//Default user list rendering
let contactListItems = `
${loggedInUser?.contacts.map((user) => {
return (
`
<li id="${user?.email}"
class="userItem grid grid-cols-2 cursor-pointer justify-center items-center p-3 border-b border-gray-200 hover:bg-gray-300 duration-300 dark:hover:bg-gray-700 dark:border-gray-700">
<img src="${user?.avatar}"
alt="" class="ml-4 w-[50px] aspect-square rounded-full">
<p class='text-xl max-sm:ml-[-30%]'>${user?.username}</p>
</li>
`
)
}).join("")
}
`
if (document.querySelector("#chatList")) {
document.querySelector("#chatList").innerHTML = "";
document.querySelector("#chatList").insertAdjacentHTML("afterbegin", contactListItems);
}
const listItemClicked = async (event) => {
secondPerson = users.filter((user) => {
if (user.email == event.currentTarget.id) {
return user;
}
})
secondPerson = secondPerson[0];
let newChat = {
uid: loggedInUser.uid + secondPerson.uid,
email: loggedInUser.email + "-" + secondPerson.email,
name: loggedInUser.username + "-" + secondPerson.username,
chats: []
}
let res = await fetch(uri + "/chats");
chatsData = await res.json();
chats = chatsData;
let foundChat = chats.filter((chat) => {
if (chat?.uid == loggedInUser.uid + secondPerson.uid) {
return chat;
}
})[0]
let selectedMessage = {};
const preUpdating = async () => {
let wholeChatSection = document.querySelector(".chat");
const updateMessages = async () => {
await fetch(uri + "/chats/" + foundChat?.id)
.then(res => res.json())
.then(data => foundChat = data)
.then(() => {
let chatMessages = `
<nav
class="fixed top-0 right-0 max-sm:mt-[0px] z-40 lg:w-[75%] md:w-[66.67%] sm:w-[50%] max-sm:w-[100%] bg-blue-500 dark:bg-gray-800 text-white p-3 border-b border-gray-400 flex justify-left items-center shadow-md shadow-gray-300 max-sm:shadow-none dark:shadow-none dark:border-gray-500">
<button id="backToContactsListBtn"
class="w-[50px] aspect-square text-xl text-gray-100 rounded-full focus:border sm:hidden md:hidden lg:hidden">
<i class="fa fa-arrow-left"></i>
</button>
<button id="chatProfile" class="w-[50px] aspect-square text-xl text-gray-600 dark:text-gray-100 ml-2">
<img src="${secondPerson?.avatar}" alt="" class="text-center w-[50px] h-[50px] mr-5 rounded-full" />
</button>
<p class="text-xl text-right ml-3">${secondPerson?.username}</p>
</nav>
<ul id="innerChat" class="mt-[100px] lg:mb-[140px] md:mb-[140px] sm:mb-[140px] max-sm:mb-[180px]">
${foundChat.chats?.map((chat) => {
return (
`
${chat?.author == loggedInUser?.email ?
`
<li id="${chat?.uid}" class="messageItem mr-[30%] flex grid-cols-2 justify-center items-center">
<img src="${loggedInUser?.avatar}" alt="" class="text-center w-[50px] h-[50px] mr-5 rounded-full" />
<div class="rounded-xl p-5 bg-cyan-500 my-2 dark:bg-cyan-800 dark:text-gray-100">
<p>
${chat?.content}
</p>
</div>
<button class="text-center w-[25px] h-[25px] bg-cyan-600 dark:bg-gray-700 text-gray-200 ml-2 rounded-full"><i class="fa fa-trash"></i></button>
</li>
` :
`
<li class="ml-[30%] flex grid-cols-2 justify-center items-center">
<div class="rounded-xl p-5 bg-white my-2 dark:bg-gray-700 dark:text-gray-100">
<p>${chat?.content}</p>
</div>
<img src="${secondPerson?.avatar}" alt="" class="text-center w-[50px] h-[50px] ml-5 rounded-full" />
</li>
`
}
`
)
}).join("")
}
</ul>
<nav
class="sending fixed bottom-0 right-0 mt-[75px] lg:w-[75%] md:w-[66.67%] sm:w-[50%] max-sm:w-[100%] bg-gray-100 dark:bg-gray-800 p-1 border-b border-gray-400 dark:border-gray-700 flex justify-center items-center shadow-md shadow-gray-300">
<div class="flex grid-cols-1 w-full justify-center">
<input type="text" id="messageInput"
class="shadow-sm break-before-all bg-gray-50 border border-gray-400 text-gray-900 text-sm rounded-full focus:ring-blue-500 focus:border-blue-500 block w-[72%] p-2.5 dark:bg-gray-800 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 dark:shadow-sm-light"
placeholder="Type your message" />
<button id="sendBtn" class="w-[50px] aspect-square text-xl text-gray-600 dark:text-gray-100">
<i class="fa fa-send"></i>
</button>
</div>
</nav>
`
document.querySelector("#chat").innerHTML = "";
document.querySelector("#chat").insertAdjacentHTML("afterbegin", chatMessages);
})
.then(() => {
preSending();
})
.then(() => {
preDeleting();
})
.then(() => {
preUpdating();
})
.then(() => {
document.querySelector("#backToContactsListBtn").addEventListener("click", async (event) => {
event.stopPropagation();
document.querySelector("#chat").classList.add("hidden");
document.querySelector("#chatPreview").classList.remove("hidden");
document.querySelector(".chat").classList.add("max-sm:hidden");
document.querySelector(".chatList").classList.remove("max-sm:hidden");
})
document.querySelector("#backToContactsListBtn").addEventListener("touchmove", async (event) => {
event.stopPropagation();
})
})
}
wholeChatSection.addEventListener("click", () => updateMessages());
//wholeChatSection.addEventListener("touchmove", () => updateMessages());
}
const preDeleting = async () => {
let deleteBtnEl = document.querySelectorAll(".messageItem");
const deleteMessage = async (el) => {
await fetch(uri + "/chats/" + foundChat?.id)
.then(res => res.json())
.then(data => foundChat = data)
.then(async () => {
selectedMessage = foundChat?.chats.filter((chat) => {
if(chat.uid == parseInt(el.id) && chat.author == loggedInUser?.email) {
return chat;
}
})[0]
foundChat.chats = foundChat?.chats.filter((chat) => {
if (chat.uid != parseInt(el.id)) {
return chat;
}
})
})
.then(async () => {
if(selectedMessage?.uid == parseInt(el.id)) {
await fetch(uri + "/chats/" + foundChat?.id, {
method: "PUT", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: "follow", // manual, *follow, error
referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(foundChat), // body data type must match "Content-Type" header
})
}
})
.then(() => {
let chatMessages = `
<nav
class="fixed top-0 right-0 max-sm:mt-[0px] z-40 lg:w-[75%] md:w-[66.67%] sm:w-[50%] max-sm:w-[100%] bg-blue-500 dark:bg-gray-800 text-white p-3 border-b border-gray-400 flex justify-left items-center shadow-md shadow-gray-300 max-sm:shadow-none dark:shadow-none dark:border-gray-500">
<button id="backToContactsListBtn"
class="w-[50px] aspect-square text-xl text-gray-100 rounded-full focus:border sm:hidden md:hidden lg:hidden">
<i class="fa fa-arrow-left"></i>
</button>
<button id="chatProfile" class="w-[50px] aspect-square text-xl text-gray-600 dark:text-gray-100 ml-2">
<img src="${secondPerson?.avatar}" alt="" class="text-center w-[50px] h-[50px] mr-5 rounded-full" />
</button>
<p class="text-xl text-right ml-3">${secondPerson?.username}</p>
</nav>
<ul id="innerChat" class="mt-[100px] lg:mb-[140px] md:mb-[140px] sm:mb-[140px] max-sm:mb-[180px]">
${foundChat.chats?.map((chat) => {
return (
`
${chat?.author == loggedInUser?.email ?
`
<li id="${chat?.uid}" class="messageItem mr-[30%] flex grid-cols-2 justify-center items-center">
<img src="${loggedInUser?.avatar}" alt="" class="text-center w-[50px] h-[50px] mr-5 rounded-full" />
<div class="rounded-xl p-5 bg-cyan-500 my-2 dark:bg-cyan-800 dark:text-gray-100">
<p>
${chat?.content}
</p>
</div>
<button class="text-center w-[25px] h-[25px] bg-cyan-600 dark:bg-gray-700 text-gray-200 ml-2 rounded-full"><i class="fa fa-trash"></i></button>
</li>
` :
`
<li class="ml-[30%] flex grid-cols-2 justify-center items-center">
<div class="rounded-xl p-5 bg-white my-2 dark:bg-gray-700 dark:text-gray-100">
<p>${chat?.content}</p>
</div>
<img src="${secondPerson?.avatar}" alt="" class="text-center w-[50px] h-[50px] ml-5 rounded-full" />
</li>
`
}
`
)
}).join("")
}
</ul>
<nav
class="sending fixed bottom-0 right-0 mt-[75px] lg:w-[75%] md:w-[66.67%] sm:w-[50%] max-sm:w-[100%] bg-gray-100 dark:bg-gray-800 p-1 border-b border-gray-400 dark:border-gray-700 flex justify-center items-center shadow-md shadow-gray-300">
<div class="flex grid-cols-1 w-full justify-center">
<input type="text" id="messageInput"
class="shadow-sm break-before-all bg-gray-50 border border-gray-400 text-gray-900 text-sm rounded-full focus:ring-blue-500 focus:border-blue-500 block w-[72%] p-2.5 dark:bg-gray-800 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 dark:shadow-sm-light"
placeholder="Type your message" />
<button id="sendBtn" class="w-[50px] aspect-square text-xl text-gray-600 dark:text-gray-100">
<i class="fa fa-send"></i>
</button>
</div>
</nav>
`
document.querySelector("#chat").innerHTML = "";
document.querySelector("#chat").insertAdjacentHTML("afterbegin", chatMessages);
})
.then(() => {
preSending();
})
.then(() => {
preDeleting();
})
.then(() => {
preUpdating();
})
.then(() => {
document.querySelector("#backToContactsListBtn").addEventListener("click", async (event) => {
event.stopPropagation();
document.querySelector("#chat").classList.add("hidden");
document.querySelector("#chatPreview").classList.remove("hidden");
document.querySelector(".chat").classList.add("max-sm:hidden");
document.querySelector(".chatList").classList.remove("max-sm:hidden");
})
document.querySelector("#backToContactsListBtn").addEventListener("touchmove", async (event) => {
event.stopPropagation();
})
})
}
deleteBtnEl.forEach((el) => {
el.children[2]?.addEventListener("click", async (event) => {
event.stopPropagation();
deleteMessage(el);
})
})
}
const preSending = async () => {
let messageInputEl = document.querySelector("#messageInput");
let sendBtnEl = document.querySelector("#sendBtn");
let messageInput = "";
messageInputEl.addEventListener("change", (event) => {
messageInput = event.target.value;
})
const postMessage = async () => {
if (messageInput != "") {
let res = await fetch(uri + "/users/" + loggedInUser?.id);
loggedInUser = await res.json();
let foundContact = loggedInUser?.contacts.filter((contact) => {
if (contact.uid == secondPerson?.uid + loggedInUser?.uid) {
return contact;
}
})[0]
const finishSending = async () => {
await fetch(uri + "/chats/" + foundChat?.id, {
method: "PUT", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: "follow", // manual, *follow, error
referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify({
...foundChat,
chats: [
...foundChat?.chats,
{
uid: foundChat?.uid + Math.floor(Math.random() * 1000000000),
created: today + " at " + formatAMPM(new Date()),
edited: "",
author: loggedInUser?.email,
content: messageInput
}
]
}), // body data type must match "Content-Type" header
})
.then(async () => {
let res = await fetch(uri + "/chats");
chats = await res.json();
foundChat = chats.filter((chat) => {
if (chat?.uid == loggedInUser.uid + secondPerson.uid) {
return chat;
}
})[0]
})
.then(() => {
let chatMessages = `
<nav
class="fixed top-0 right-0 max-sm:mt-[0px] z-40 lg:w-[75%] md:w-[66.67%] sm:w-[50%] max-sm:w-[100%] bg-blue-500 dark:bg-gray-800 text-white p-3 border-b border-gray-400 flex justify-left items-center shadow-md shadow-gray-300 max-sm:shadow-none dark:shadow-none dark:border-gray-500">
<button id="backToContactsListBtn"
class="w-[50px] aspect-square text-xl text-gray-100 rounded-full focus:border sm:hidden md:hidden lg:hidden">
<i class="fa fa-arrow-left"></i>
</button>
<button id="chatProfile" class="w-[50px] aspect-square text-xl text-gray-600 dark:text-gray-100 ml-2">
<img src="${secondPerson?.avatar}" alt="" class="text-center w-[50px] h-[50px] mr-5 rounded-full" />
</button>
<p class="text-xl text-right ml-3">${secondPerson?.username}</p>
</nav>
<ul id="innerChat" class="mt-[100px] lg:mb-[140px] md:mb-[140px] sm:mb-[140px] max-sm:mb-[180px]">
${foundChat.chats?.map((chat) => {
return (
`
${chat?.author == loggedInUser?.email ?
`
<li id="${chat?.uid}" class="messageItem mr-[30%] flex grid-cols-2 justify-center items-center">
<img src="${loggedInUser?.avatar}" alt="" class="text-center w-[50px] h-[50px] mr-5 rounded-full" />
<div class="rounded-xl p-5 bg-cyan-500 my-2 dark:bg-cyan-800 dark:text-gray-100">
<p>
${chat?.content}
</p>
</div>
<button class="text-center w-[25px] h-[25px] bg-cyan-600 dark:bg-gray-700 text-gray-200 ml-2 rounded-full"><i class="fa fa-trash"></i></button>
</li>
` :
`
<li class="ml-[30%] flex grid-cols-2 justify-center items-center">
<div class="rounded-xl p-5 bg-white my-2 dark:bg-gray-700 dark:text-gray-100">
<p>${chat?.content}</p>
</div>
<img src="${secondPerson?.avatar}" alt="" class="text-center w-[50px] h-[50px] ml-5 rounded-full" />
</li>
`
}
`
)
}).join("")
}
</ul>
<nav
class="sending fixed bottom-0 right-0 mt-[75px] lg:w-[75%] md:w-[66.67%] sm:w-[50%] max-sm:w-[100%] bg-gray-100 dark:bg-gray-800 p-1 border-b border-gray-400 dark:border-gray-700 flex justify-center items-center shadow-md shadow-gray-300">
<div class="flex grid-cols-1 w-full justify-center">
<input type="text" id="messageInput"
class="shadow-sm break-before-all bg-gray-50 border border-gray-400 text-gray-900 text-sm rounded-full focus:ring-blue-500 focus:border-blue-500 block w-[72%] p-2.5 dark:bg-gray-800 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 dark:shadow-sm-light"
placeholder="Type your message" />
<button id="sendBtn" class="w-[50px] aspect-square text-xl text-gray-600 dark:text-gray-100">
<i class="fa fa-send"></i>
</button>
</div>
</nav>
`
document.querySelector("#chat").innerHTML = "";
document.querySelector("#chat").insertAdjacentHTML("afterbegin", chatMessages);
document.querySelector("#backToContactsListBtn").addEventListener("click", (event) => {
event.stopPropagation();
document.querySelector("#chat").classList.add("hidden");
document.querySelector("#chatPreview").classList.remove("hidden");
document.querySelector(".chat").classList.add("max-sm:hidden");
document.querySelector(".chatList").classList.remove("max-sm:hidden");
})
document.querySelector("#backToContactsListBtn").addEventListener("touchmove", async (event) => {
event.stopPropagation();
})
})
.then(() => {
preDeleting();
})
.then(() => {
preSending();
})
.then(() => {
preUpdating();
})
.then(() => {
messageInputEl.value = "";
messageInput = "";
})
}
if (foundContact?.uid == secondPerson?.uid + loggedInUser?.uid) {
finishSending();
} else {
await fetch(uri + "/users/" + loggedInUser?.id, {
method: "PUT", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: "follow", // manual, *follow, error
referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify({
...loggedInUser,
contacts: [
...loggedInUser?.contacts,
{
uid: secondPerson?.uid + loggedInUser?.uid,
date: today + " at " + formatAMPM(new Date()),
username: secondPerson?.username,
email: secondPerson?.email,
avatar: secondPerson?.avatar
}
]
}), // body data type must match "Content-Type" header
})
.then(async () => {
let res = await fetch(uri + "/users/" + secondPerson?.id);
secondPerson = await res.json();
let secondPersonFoundContact = secondPerson?.contacts.filter((contact) => {
if (contact.uid == secondPerson?.uid + loggedInUser?.uid) {
return contact;
}
})[0]
if (secondPersonFoundContact?.uid != secondPerson?.uid + loggedInUser?.uid) {
await fetch(uri + "/users/" + secondPerson?.id, {
method: "PUT", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: "follow", // manual, *follow, error
referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify({
...secondPerson,
contacts: [
...secondPerson?.contacts,
{
uid: loggedInUser?.uid + secondPerson?.uid,
date: today + " at " + formatAMPM(new Date()),
username: loggedInUser?.username,
email: loggedInUser?.email,
avatar: loggedInUser?.avatar
}
]
}), // body data type must match "Content-Type" header
})
}
})
.then(() => {
finishSending();
})
}
}
}
sendBtnEl.addEventListener("click", async (event) => {
event.stopPropagation();
postMessage()
});
messageInputEl.addEventListener("keyup", (event) => {
event.stopPropagation();
if (event.key == "Enter") {
postMessage();
}
})
document.querySelector(".sending").addEventListener("click", (event) => {
event.stopPropagation();
})
document.querySelector(".sending").addEventListener("touchmove", (event) => {
event.stopPropagation();
})
}
if (foundChat?.uid != loggedInUser.uid + secondPerson.uid) {
//Creating Chat
await fetch(uri + "/chats", {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: "follow", // manual, *follow, error
referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(newChat), // body data type must match "Content-Type" header
})
.then(() => {
console.log("Success");
})
.then(() => {
let chatMessages = `
<nav
class="fixed top-0 right-0 max-sm:mt-[0px] z-40 lg:w-[75%] md:w-[66.67%] sm:w-[50%] max-sm:w-[100%] bg-blue-500 dark:bg-gray-800 text-white p-3 border-b border-gray-400 flex justify-left items-center shadow-md shadow-gray-300 max-sm:shadow-none dark:shadow-none dark:border-gray-500">
<button id="backToContactsListBtn"
class="w-[50px] aspect-square text-xl text-gray-100 rounded-full focus:border sm:hidden md:hidden lg:hidden">
<i class="fa fa-arrow-left"></i>
</button>
<button id="chatProfile" class="w-[50px] aspect-square text-xl text-gray-600 dark:text-gray-100 ml-2">
<img src="${secondPerson?.avatar}" alt="" class="text-center w-[50px] h-[50px] mr-5 rounded-full" />
</button>
<p class="text-xl text-right ml-3">${secondPerson?.username}</p>
</nav>
<ul id="innerChat" class="mt-[100px] lg:mb-[140px] md:mb-[140px] sm:mb-[140px] max-sm:mb-[180px]">
${foundChat.chats?.map((chat) => {
return (
`
${chat?.author == loggedInUser?.email ?
`
<li id="${chat?.uid}" class="messageItem mr-[30%] flex grid-cols-2 justify-center items-center">
<img src="${loggedInUser?.avatar}" alt="" class="text-center w-[50px] h-[50px] mr-5 rounded-full" />
<div class="rounded-xl p-5 bg-cyan-500 my-2 dark:bg-cyan-800 dark:text-gray-100">
<p>
${chat?.content}
</p>
</div>
<button class="text-center w-[25px] h-[25px] bg-cyan-600 dark:bg-gray-700 text-gray-200 ml-2 rounded-full"><i class="fa fa-trash"></i></button>
</li>
` :
`
<li class="ml-[30%] flex grid-cols-2 justify-center items-center">
<div class="rounded-xl p-5 bg-white my-2 dark:bg-gray-700 dark:text-gray-100">
<p>${chat?.content}</p>
</div>
<img src="${secondPerson?.avatar}" alt="" class="text-center w-[50px] h-[50px] ml-5 rounded-full" />
</li>
`
}
`
)
}).join("")
}
</ul>
<nav
class="sending fixed bottom-0 right-0 mt-[75px] lg:w-[75%] md:w-[66.67%] sm:w-[50%] max-sm:w-[100%] bg-gray-100 dark:bg-gray-800 p-1 border-b border-gray-400 dark:border-gray-700 flex justify-center items-center shadow-md shadow-gray-300">
<div class="flex grid-cols-1 w-full justify-center">
<input type="text" id="messageInput"
class="shadow-sm break-before-all bg-gray-50 border border-gray-400 text-gray-900 text-sm rounded-full focus:ring-blue-500 focus:border-blue-500 block w-[72%] p-2.5 dark:bg-gray-800 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 dark:shadow-sm-light"
placeholder="Type your message" />
<button id="sendBtn" class="w-[50px] aspect-square text-xl text-gray-600 dark:text-gray-100">
<i class="fa fa-send"></i>
</button>
</div>
</nav>
`
document.querySelector("#chat").innerHTML = "";
document.querySelector("#chat").insertAdjacentHTML("afterbegin", chatMessages);
})
.then(() => {
preSending();
})
.then(() => {
preDeleting();
})
.then(() => {
preUpdating();
})
.catch((err) => console.log(err.message))
} else {
let chatMessages = `
<nav
class="fixed top-0 right-0 max-sm:mt-[0px] z-40 lg:w-[75%] md:w-[66.67%] sm:w-[50%] max-sm:w-[100%] bg-blue-500 dark:bg-gray-800 text-white p-3 border-b border-gray-400 flex justify-left items-center shadow-md shadow-gray-300 max-sm:shadow-none dark:shadow-none dark:border-gray-500">
<button id="backToContactsListBtn"
class="w-[50px] aspect-square text-xl text-gray-100 rounded-full focus:border sm:hidden md:hidden lg:hidden">
<i class="fa fa-arrow-left"></i>
</button>
<button id="chatProfile" class="w-[50px] aspect-square text-xl text-gray-600 dark:text-gray-100 ml-2">
<img src="${secondPerson?.avatar}" alt="" class="text-center w-[50px] h-[50px] mr-5 rounded-full" />
</button>
<p class="text-xl text-right ml-3">${secondPerson?.username}</p>
</nav>
<ul id="innerChat" class="mt-[100px] lg:mb-[140px] md:mb-[140px] sm:mb-[140px] max-sm:mb-[180px]">
${foundChat.chats?.map((chat) => {
return (
`
${chat?.author == loggedInUser?.email ?
`
<li id="${chat?.uid}" class="messageItem mr-[30%] flex grid-cols-2 justify-center items-center">
<img src="${loggedInUser?.avatar}" alt="" class="text-center w-[50px] h-[50px] mr-5 rounded-full" />
<div class="rounded-xl p-5 bg-cyan-500 my-2 dark:bg-cyan-800 dark:text-gray-100">
<p>
${chat?.content}
</p>
</div>
<button class="text-center w-[25px] h-[25px] bg-cyan-600 dark:bg-gray-700 text-gray-200 ml-2 rounded-full"><i class="fa fa-trash"></i></button>
</li>
` :
`
<li class="ml-[30%] flex grid-cols-2 justify-center items-center">
<div class="rounded-xl p-5 bg-white my-2 dark:bg-gray-700 dark:text-gray-100">
<p>${chat?.content}</p>
</div>
<img src="${secondPerson?.avatar}" alt="" class="text-center w-[50px] h-[50px] ml-5 rounded-full" />
</li>
`
}
`
)
}).join("")
}
</ul>
<nav
class="sending fixed bottom-0 right-0 mt-[75px] lg:w-[75%] md:w-[66.67%] sm:w-[50%] max-sm:w-[100%] bg-gray-100 dark:bg-gray-800 p-1 border-b border-gray-400 dark:border-gray-700 flex justify-center items-center shadow-md shadow-gray-300">
<div class="flex grid-cols-1 w-full justify-center">
<input type="text" id="messageInput"
class="shadow-sm break-before-all bg-gray-50 border border-gray-400 text-gray-900 text-sm rounded-full focus:ring-blue-500 focus:border-blue-500 block w-[72%] p-2.5 dark:bg-gray-800 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 dark:shadow-sm-light"
placeholder="Type your message" />
<button id="sendBtn" class="w-[50px] aspect-square text-xl text-gray-600 dark:text-gray-100">
<i class="fa fa-send"></i>
</button>
</div>
</nav>
`
document.querySelector("#chat").innerHTML = "";
document.querySelector("#chat").insertAdjacentHTML("afterbegin", chatMessages);
preSending();
preDeleting();
preUpdating();
}
if (document.querySelector(".chat").classList.contains("max-sm:hidden")) {
document.querySelector(".chat").classList.remove("max-sm:hidden");
document.querySelector(".chatList").classList.add("max-sm:hidden");
} else {
document.querySelector(".chat").classList.add("max-sm:hidden");
document.querySelector(".chatList").classList.remove("max-sm:hidden");
}
if (document.querySelector("#chat").classList.contains("hidden")) {
document.querySelector("#chat").classList.remove("hidden");
document.querySelector("#chatPreview").classList.add("hidden");
}
document.querySelector("#backToContactsListBtn").addEventListener("click", async (event) => {
event.stopPropagation();
document.querySelector("#chat").classList.add("hidden");
document.querySelector("#chatPreview").classList.remove("hidden");
document.querySelector(".chat").classList.add("max-sm:hidden");
document.querySelector(".chatList").classList.remove("max-sm:hidden");
})
document.querySelector("#backToContactsListBtn").addEventListener("touchmove", async (event) => {
event.stopPropagation();
})
}
document.querySelectorAll(".userItem").forEach((el) => {
el.addEventListener("click", listItemClicked)
});
//Search system
let searchInputEl = document.querySelector("#searchInput");
let searchInput = "";
searchInputEl.addEventListener("change", async (event) => {
searchInput = event.target.value;
if (event.target.value == "") {
let res = await fetch(uri + "/users/" + loggedInUser?.id);
loggedInUser = await res.json();
contactListItems = `
${loggedInUser?.contacts.map((user) => {
return (
`
<li id="${user?.email}"
class="userItem grid grid-cols-2 cursor-pointer justify-center items-center p-3 border-b border-gray-200 hover:bg-gray-300 duration-300 dark:hover:bg-gray-700 dark:border-gray-700">
<img src="${user?.avatar}"
alt="" class="ml-4 w-[50px] aspect-square rounded-full">
<p class='text-xl max-sm:ml-[-30%]'>${user?.username}</p>
</li>
`
)
}).join("")
}
`
document.querySelector("#chatList").innerHTML = "";
document.querySelector("#chatList").insertAdjacentHTML("afterbegin", contactListItems);
document.querySelectorAll(".userItem").forEach((el) => {
el.addEventListener("click", listItemClicked)
});
} else {
document.querySelectorAll(".userItem").forEach((el) => {
el.addEventListener("click", listItemClicked)
});
}
})
const searchUser = async () => {
if (searchInput == "") {
let res = await fetch(uri + "/users/" + loggedInUser?.id);
loggedInUser = await res.json();
contactListItems = `
${loggedInUser?.contacts.map((user) => {
return (
`
<li id="${user?.email}"
class="userItem grid grid-cols-2 cursor-pointer justify-center items-center p-3 border-b border-gray-200 hover:bg-gray-300 duration-300 dark:hover:bg-gray-700 dark:border-gray-700">
<img src="${user?.avatar}"
alt="" class="ml-4 w-[50px] aspect-square rounded-full">
<p class='text-xl max-sm:ml-[-30%]'>${user?.username}</p>
</li>
`
)
}).join("")
}
`
document.querySelector("#chatList").innerHTML = "";
document.querySelector("#chatList").insertAdjacentHTML("afterbegin", contactListItems);
document.querySelectorAll(".userItem").forEach((el) => {
el.addEventListener("click", listItemClicked)
});
} else if (searchInput != "") {
let foundUsers = users.filter((user) => {
if (searchInput == "") {
return null;
} else if (user.username.includes(searchInput) || user.username.includes(searchInput.toUpperCase()) || user.username.includes(searchInput.toLowerCase()) || user.email.includes(searchInput) || user.email.includes(searchInput.toUpperCase()) || user.email.includes(searchInput.toLowerCase())) {
return user;
}
})
let searchListItems = `
${foundUsers.map((user) => {
return (
`
<li id="${user?.email}"
class="userItem grid grid-cols-2 cursor-pointer justify-center items-center p-3 border-b border-gray-200 hover:bg-gray-300 duration-300 dark:hover:bg-gray-700 dark:border-gray-700">
<img src="${user?.avatar}"
alt="" class="ml-4 w-[50px] aspect-square rounded-full">
<p class='text-xl max-sm:ml-[-30%]'>${user?.username}</p>
</li>
`
)
}).join("")
}
`
document.querySelector("#chatList").innerHTML = "";
document.querySelector("#chatList").insertAdjacentHTML("afterbegin", searchListItems);
//Create a chat and add that user to your and yourself to his/her contacts
let res = await fetch(uri + "/chats");
chats = await res.json();
document.querySelectorAll(".userItem").forEach((el) => {
el.addEventListener("click", listItemClicked)
});
}
}
document.querySelector("#searchBtn").addEventListener("click", searchUser);
searchInputEl.addEventListener("keyup", (event) => {
if (event.key == "Enter") {
searchUser();
}
})
//Toggle between Signup page and Login page
const toggleSignupLogin = () => {
const Signup = document.querySelector(".signup");
const Login = document.querySelector(".login");
if (Signup.classList.contains("hidden")) {
Signup.classList.remove("hidden");
Login.classList.add("hidden");
} else if (Login.classList.contains("hidden")) {
Signup.classList.add("hidden");
Login.classList.remove("hidden");
}
}
document.querySelector("#toggleSignup")?.addEventListener("click", toggleSignupLogin);
document.querySelector("#toggleLogin")?.addEventListener("click", toggleSignupLogin);
//File picker initialization
const client = filestack.init("AWOK4L9h4SROT147VanQQz");
if(localStorage.getItem("theme") == "light") {
document.documentElement.classList.remove("dark");
document.querySelector("body").classList.remove("dark:bg-gray-700");
if(document.querySelector(".chat")){
document.querySelector(".chat").style.backgroundImage = "url('https://wallpapershome.com/images/pages/pic_h/24806.jpg')"
}
} else if(localStorage.getItem("theme") == "dark") {
document.documentElement.classList.add("dark");
document.querySelector("body").classList.add("dark:bg-gray-700");
if(document.querySelector(".chat")) {
document.querySelector(".chat").style.backgroundImage = "url('https://wallpapershome.com/images/pages/pic_h/15469.jpg')"
}
}
document.querySelector("#toggleThemeBtn").addEventListener("click", () => {
if(localStorage.getItem("theme") == "light") {
localStorage.setItem("theme", "dark");