@pubuduth-aplicy/chat-ui 2.1.32 → 2.1.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pubuduth-aplicy/chat-ui",
3
- "version": "2.1.32",
3
+ "version": "2.1.34",
4
4
  "description": "This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.",
5
5
  "license": "ISC",
6
6
  "author": "",
@@ -21,7 +21,6 @@ const Message = ({ message }: MessageProps) => {
21
21
  const fromMe = message.senderId === userId;
22
22
  const bubbleBgColor = fromMe ? "chatMessagesBubble_me" : "chatMessagesBubble_Other";
23
23
  const alignItems = fromMe ? "chatMessagesBubble_me" : "chatMessagesBubble_Other";
24
- console.log('messagedis',message);
25
24
 
26
25
  const date = new Date(message.createdAt);
27
26
  const hours = date.getUTCHours();
@@ -3,12 +3,32 @@ import { useEffect } from "react";
3
3
  import MessageInput from "./MessageInput";
4
4
  import Messages from "./Messages";
5
5
  import useChatUIStore from "../../stores/Zustant";
6
+ import { useChatContext } from "../../providers/ChatProvider";
6
7
  // import { Chat, CaretLeft } from "@phosphor-icons/react";
7
8
  // import { useAuthContext } from "../../context/AuthContext";
8
9
 
9
10
 
10
11
  const MessageContainer = () => {
11
- const { selectedConversation, setSelectedConversation } = useChatUIStore();
12
+ const { selectedConversation, setSelectedConversation ,onlineUsers, setOnlineUsers } = useChatUIStore();
13
+ const {socket} = useChatContext();
14
+
15
+ useEffect(() => {
16
+ if (!socket) return;
17
+
18
+ const handleOnlineUsers = (users: string[]) => {
19
+ setOnlineUsers(users);
20
+ };
21
+
22
+ socket.on("getOnlineUsers", handleOnlineUsers);
23
+
24
+ return () => {
25
+ socket.off("getOnlineUsers", handleOnlineUsers);
26
+ };
27
+ }, [socket, setOnlineUsers]);
28
+
29
+ const isUserOnline = selectedConversation?.participantDetails?._id &&
30
+ onlineUsers?.includes(selectedConversation.participantDetails._id);
31
+
12
32
 
13
33
  useEffect(() => {
14
34
  // cleanup function (unmounts)
@@ -33,7 +53,9 @@ const MessageContainer = () => {
33
53
  <p className="chatMessageContainerOutterDiv_name">
34
54
  {selectedConversation.participantDetails.firstname}
35
55
  </p>
36
- <p className="text-sm text-[#12bbb5]">Online</p>
56
+ <p className="text-sm text-[#12bbb5]">
57
+ {isUserOnline ? "Online" : "Offline"}
58
+ </p>
37
59
  </div>
38
60
  </div>
39
61
  {/* <h4 className=" inline-block py-2 text-left font-sans font-semibold normal-case">Lara Abegnale</h4> */}
@@ -26,48 +26,64 @@ const MessageInput = () => {
26
26
 
27
27
  useEffect(() => {
28
28
  if (!socket) return;
29
-
30
- const handleTyping = ({ userid }: { userid: string }) => {
31
- if (userid !== userId) {
32
- setTypingUser(userid);
29
+
30
+ if (message.trim() !== "") {
31
+ setIsTyping(true);
32
+ socket.emit("typing", { chatId: selectedConversation?._id, userId });
33
+ }
34
+
35
+ const typingTimeout = setTimeout(() => {
36
+ if (message.trim() === "") {
37
+ setIsTyping(false);
38
+ socket.emit("stopTyping", {
39
+ chatId: selectedConversation?._id,
40
+ userId,
41
+ });
33
42
  }
43
+ }, 2000);
44
+
45
+ return () => clearTimeout(typingTimeout);
46
+ }, [message, socket, selectedConversation?._id, userId]);
47
+
48
+ useEffect(() => {
49
+ if (!socket) return;
50
+
51
+ const handleTyping = ({ userId }: { userId: string }) => {
52
+ setTypingUser(userId);
34
53
  };
35
-
36
- const handleStopTyping = ({ userid }: { userid: string }) => {
37
- if (userid === typingUser) {
38
- setTypingUser(null);
39
- }
54
+
55
+ const handleStopTyping = ({ userId }: { userId: string }) => {
56
+ setTypingUser((prev) => (prev === userId ? null : prev));
40
57
  };
41
-
58
+
42
59
  socket.on("typing", handleTyping);
43
60
  socket.on("stopTyping", handleStopTyping);
44
-
61
+
45
62
  return () => {
46
63
  socket.off("typing", handleTyping);
47
64
  socket.off("stopTyping", handleStopTyping);
48
65
  };
49
- }, [socket, typingUser, userId]);
66
+ }, [socket]);
50
67
 
51
- useEffect(() => {
52
- if (message) {
53
- setIsTyping(true);
54
- socket.emit("typing", {
55
- chatId: selectedConversation?._id,
56
- userId,
57
- });
58
- }
59
-
60
- // Clear typing indicator when user stops typing
61
- const typingTimeout = setTimeout(() => {
62
- if (message === "") {
63
- setIsTyping(false);
64
- socket.emit("stopTyping", { chatId: selectedConversation?._id, userId });
65
- }
66
- }, 2000);
67
-
68
- return () => clearTimeout(typingTimeout);
69
- }, [message, socket, selectedConversation?._id, userId]);
70
-
68
+ // useEffect(() => {
69
+ // if (message) {
70
+ // setIsTyping(true);
71
+ // socket.emit("typing", {
72
+ // chatId: selectedConversation?._id,
73
+ // userId,
74
+ // });
75
+ // }
76
+
77
+ // // Clear typing indicator when user stops typing
78
+ // const typingTimeout = setTimeout(() => {
79
+ // if (message === "") {
80
+ // setIsTyping(false);
81
+ // socket.emit("stopTyping", { chatId: selectedConversation?._id, userId });
82
+ // }
83
+ // }, 2000);
84
+
85
+ // return () => clearTimeout(typingTimeout);
86
+ // }, [message, socket, selectedConversation?._id, userId]);
71
87
 
72
88
  const handleSubmit = useCallback(
73
89
  async (e: any) => {
@@ -79,7 +95,7 @@ const MessageInput = () => {
79
95
  console.log("📤 Sending message:", message);
80
96
 
81
97
  if (selectedConversation?._id) {
82
- sendMessage({
98
+ sendMessage({
83
99
  chatId: selectedConversation.participantDetails._id,
84
100
  senderId: userId,
85
101
  message,
@@ -116,10 +132,16 @@ const MessageInput = () => {
116
132
  </button>
117
133
  </div>
118
134
 
119
- {typingUser && typingUser !== userId && !isSending &&(
120
- <div className="typingIndicator">Someone is typing...</div>
135
+ {typingUser && typingUser !== userId && !isSending && (
136
+ <div className="typingIndicator">
137
+ <div className="loader">
138
+ <div className="ball" />
139
+ <div className="ball" />
140
+ <div className="ball" />
141
+ typing
142
+ </div>
143
+ </div>
121
144
  )}
122
-
123
145
  </form>
124
146
  );
125
147
  };
@@ -1,5 +1,5 @@
1
1
  /* eslint-disable @typescript-eslint/no-explicit-any */
2
- import { useEffect, useRef, useState } from "react";
2
+ import { useEffect, useRef } from "react";
3
3
  // import useGetMessages from "../../hooks/useGetMessages";
4
4
  // import MessageSkeleton from "../skeletons/MessageSkeleton";
5
5
  import Message from "./Message";
@@ -9,25 +9,27 @@ import useChatUIStore from "../../stores/Zustant";
9
9
  // import useListenMessages from "../../hooks/useListenMessages";
10
10
 
11
11
  const Messages = () => {
12
- const { selectedConversation } = useChatUIStore()
12
+ const { selectedConversation,setMessages,messages } = useChatUIStore()
13
13
  const {userId,socket}=useChatContext()
14
- const { data: messages, isLoading, isError, error } = useMessages(selectedConversation?._id, userId);
15
- const [localMessages, setLocalMessages] = useState<any[]>([]);
14
+ const { data, isLoading, isError, error } = useMessages(selectedConversation?._id, userId);
16
15
 
17
16
  const lastMessageRef = useRef<HTMLDivElement>(null);
18
17
 
19
- useEffect(() => {
20
- if (messages?.messages) {
21
- setLocalMessages(messages.messages);
18
+
19
+ useEffect(() => {
20
+ if (data) {
21
+ setMessages(data.messages);
22
22
  }
23
- }, [messages]);
23
+ }, [selectedConversation?._id,data]);
24
24
 
25
25
  // Listen for new messages from the server
26
26
  useEffect(() => {
27
- if (!socket) return;
27
+ if (!socket || !selectedConversation?._id) return;
28
28
 
29
- const handleNewMessage = (newMessage: any) => {
30
- setLocalMessages((prevMessages) => [...prevMessages, newMessage]);
29
+ const handleNewMessage = (newMessage:any) => {
30
+ newMessage.shouldShake = true;
31
+ console.log("📩 New message received:", newMessage);
32
+ setMessages([...messages, newMessage[1]]);
31
33
  };
32
34
 
33
35
  socket.on("newMessage", handleNewMessage);
@@ -35,13 +37,13 @@ const Messages = () => {
35
37
  return () => {
36
38
  socket.off("newMessage", handleNewMessage);
37
39
  };
38
- }, [socket]);
40
+ }, [socket,setMessages, messages]);
39
41
 
40
- useEffect(() => {
42
+ useEffect(() => {
41
43
  setTimeout(() => {
42
- lastMessageRef.current?.scrollIntoView({ behavior: "smooth" });
44
+ lastMessageRef.current?.scrollIntoView({ behavior: "smooth" });
43
45
  }, 100);
44
- }, [messages]);
46
+ }, [messages]);
45
47
 
46
48
  if (isLoading) {
47
49
  return <p>Loading messages...</p>;
@@ -51,10 +53,13 @@ const Messages = () => {
51
53
  return <p>Error: {error?.message}</p>;
52
54
  }
53
55
 
56
+ console.log("📩 Messages:", messages);
57
+ console.log("📩 Messages Length:", messages?.length);
58
+
54
59
  return (
55
60
  <div className="chatMessages">
56
- {localMessages.length > 0 ? (
57
- localMessages.map((message: any) => (
61
+ {messages?.length > 0 ? (
62
+ messages?.map((message: any) => (
58
63
  <div key={message._id} ref={lastMessageRef}>
59
64
  <Message message={message} />
60
65
  </div>
@@ -1,3 +1,4 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
1
2
  import React, {
2
3
  createContext,
3
4
  useContext,
@@ -28,6 +29,7 @@ interface ChatContextType {
28
29
  socket: Socket;
29
30
  // cryptoUtils: CryptoUtils;
30
31
  userId: string;
32
+ onlineUsers: any;
31
33
  }
32
34
 
33
35
  const ChatContext = createContext<ChatContextType | null>(null);
@@ -38,16 +40,41 @@ export const ChatProvider: React.FC<ChatProviderProps> = ({
38
40
  }) => {
39
41
  const socketRef = useRef<Socket | null>(null);
40
42
  const [socket, setSocket] = useState<Socket | null>(null);
43
+ const [onlineUsers, setOnlineUsers] = useState([]);
41
44
  const apiUrl = import.meta.env.VITE_APP_BACKEND_PORT;
45
+ console.log("API URL:", apiUrl);
42
46
 
43
47
  useEffect(() => {
44
48
  if (!socketRef.current) {
45
49
  console.log("🔌 Creating new socket connection...");
46
- const socketInstance = io(apiUrl, { auth: { userId } });
50
+ const socketInstance = io('http://localhost:3001', {
51
+ query: {
52
+ userId: userId,
53
+ },
54
+ transports: ["websocket"],
55
+ });
56
+
57
+ // Log connection events
58
+ socketInstance.on("connect", () => {
59
+ console.log("✅ Connected to server with socket ID:", socketInstance.id);
60
+ });
61
+
62
+ socketInstance.on("connect_error", (error) => {
63
+ console.error("❌ Connection error:", error);
64
+ });
65
+
66
+ socketInstance.on("disconnect", () => {
67
+ console.log("❌ Disconnected from server");
68
+ });
69
+
47
70
  socketRef.current = socketInstance;
48
71
  setSocket(socketInstance);
49
72
  }
50
-
73
+
74
+ socket?.on("getOnlineUsers", (users) => {
75
+ setOnlineUsers(users);
76
+ });
77
+
51
78
  return () => {
52
79
  console.log("❌ Disconnecting socket...");
53
80
  socketRef.current?.disconnect();
@@ -57,12 +84,13 @@ export const ChatProvider: React.FC<ChatProviderProps> = ({
57
84
 
58
85
  if (!socket) return null;
59
86
 
87
+
60
88
  // const apiClient = new ApiClient(apiUrl);
61
89
  // const s3Client = new S3Client(s3Config);
62
90
  // const cryptoUtils = new CryptoUtils();
63
91
 
64
92
  return (
65
- <ChatContext.Provider value={{ socket, userId }}>
93
+ <ChatContext.Provider value={{ socket, userId,onlineUsers }}>
66
94
  {children}
67
95
  </ChatContext.Provider>
68
96
  );
@@ -1,13 +1,6 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
1
2
  import {create} from 'zustand';
2
3
 
3
- // interface ChatUIState {
4
- // isChatOpen: boolean;
5
- // unreadCount: number;
6
- // toggleChat: () => void;
7
- // incrementUnreadCount: () => void;
8
- // resetUnreadCount: () => void;
9
- // }
10
-
11
4
  interface ChatUIState {
12
5
  isChatOpen: boolean;
13
6
  unreadCount: number;
@@ -20,9 +13,13 @@ interface ChatUIState {
20
13
  }
21
14
  _id:string;
22
15
  } | null;
23
- setSelectedConversation: (selectedConversation: { _id: string; profilePic: string; username: string; } | null) => void;
16
+ setSelectedConversation: (selectedConversation: { participantDetails: { _id: string; profilePic: string; firstname: string; idpic: string; }; _id: string; } | null) => void;
17
+ messages: any[];
18
+ setMessages: (messages: any[]) => void;
24
19
  toggleChat: () => void;
25
20
  incrementUnreadCount: () => void;
21
+ onlineUsers: string[];
22
+ setOnlineUsers: (users: string[]) => void;
26
23
  resetUnreadCount: () => void;
27
24
  }
28
25
 
@@ -30,8 +27,12 @@ const useChatUIStore = create<ChatUIState>((set) => ({
30
27
  isChatOpen: false,
31
28
  unreadCount: 0,
32
29
  selectedConversation: null,
30
+ messages: [],
31
+ setMessages: (messages: any) => set({ messages }),
33
32
  setSelectedConversation: (selectedConversation) => set({ selectedConversation }),
34
33
  toggleChat: () => set((state) => ({ isChatOpen: !state.isChatOpen })),
34
+ onlineUsers: [],
35
+ setOnlineUsers: (users) => set({ onlineUsers: users }),
35
36
  incrementUnreadCount: () => set((state) => ({ unreadCount: state.unreadCount + 1 })),
36
37
  resetUnreadCount: () => set({ unreadCount: 0 }),
37
38
  }));
@@ -299,7 +299,7 @@
299
299
  .chatMessageInputform {
300
300
  position: sticky;
301
301
  bottom: 0;
302
- background: #dbdbdb;
302
+ background: #eee7e7;
303
303
  padding-left: 1rem;
304
304
  padding-right: 1rem;
305
305
  padding-top: 0.25rem;
@@ -387,4 +387,59 @@
387
387
  padding-right: 2rem;
388
388
  }
389
389
 
390
- }
390
+ }
391
+
392
+ .typingIndicator{
393
+ display: flex;
394
+ align-items: center;
395
+ gap: 0.5rem;
396
+ }
397
+
398
+ /* From Uiverse.io by ashish-yadv */
399
+ .loader {
400
+ width: 60px;
401
+ display: flex;
402
+ align-items: center;
403
+ height: 100%;
404
+ margin-right: 10px;
405
+ width: 100%;
406
+ font-size: smaller;
407
+ gap: 0.5rem;
408
+ }
409
+
410
+ .ball {
411
+ width: 6px;
412
+ height: 6px;
413
+ border-radius: 50%;
414
+ background-color: #3b2dfd;
415
+ }
416
+
417
+ .ball:nth-child(1) {
418
+ animation: bounce-1 2.1s ease-in-out infinite;
419
+ }
420
+
421
+ @keyframes bounce-1 {
422
+ 50% {
423
+ transform: translateY(-3px);
424
+ }
425
+ }
426
+
427
+ .ball:nth-child(2) {
428
+ animation: bounce-3 2.1s ease-in-out 0.3s infinite;
429
+ }
430
+
431
+ @keyframes bounce-2 {
432
+ 50% {
433
+ transform: translateY(-3px);
434
+ }
435
+ }
436
+
437
+ .ball:nth-child(3) {
438
+ animation: bounce-3 2.1s ease-in-out 0.6s infinite;
439
+ }
440
+
441
+ @keyframes bounce-3 {
442
+ 50% {
443
+ transform: translateY(-3px);
444
+ }
445
+ }