+
+
+

{
/>
-
-
{selectedUser?.fullName}
+
+
{selectedUser?.fullName}
- {onlineUsers.includes(selectedUser?._id) ? "Online" : selectedUser?._id === chatBotId ? "Online" : "Offline"}
+ {isPeerTyping ? (
+
+ ) : onlineUsers.includes(selectedUser?._id) ? (
+ "Online"
+ ) : selectedUser?._id === chatBotId ? (
+ "Online"
+ ) : (
+ "Offline"
+ )}
-
diff --git a/client/src/components/createGroupModal.jsx b/client/src/components/createGroupModal.jsx
new file mode 100644
index 0000000..7916e6a
--- /dev/null
+++ b/client/src/components/createGroupModal.jsx
@@ -0,0 +1,163 @@
+import { useRef, useState } from "react";
+import { X, Camera, Loader } from "lucide-react";
+import { toast } from "react-toastify";
+import { groupStore } from "../store/groupStore.js";
+import { MemberPicker } from "./memberPicker.jsx";
+import { authStore } from "../store/authStore.js";
+
+export const CREATE_GROUP_MODAL_ID = "create_group_modal";
+
+export const CreateGroupModal = ({ onCreated }) => {
+ const { createGroup } = groupStore();
+ const { user } = authStore();
+ const [name, setName] = useState("");
+ const [iconFile, setIconFile] = useState(null);
+ const [iconPreview, setIconPreview] = useState(null);
+ const [selectedMembers, setSelectedMembers] = useState([]);
+ const [isCreating, setIsCreating] = useState(false);
+ const iconInputRef = useRef(null);
+
+ const resetForm = () => {
+ setName("");
+ setIconFile(null);
+ setIconPreview(null);
+ setSelectedMembers([]);
+ if (iconInputRef.current) iconInputRef.current.value = null;
+ };
+
+ const closeModal = () => {
+ document.getElementById(CREATE_GROUP_MODAL_ID)?.close();
+ resetForm();
+ };
+
+ const handleIconChange = (event) => {
+ const file = event.target.files[0];
+ if (!file) return;
+ if (!file.type.startsWith("image/")) {
+ toast.error("Please select an image file.");
+ return;
+ }
+ setIconFile(file);
+ const reader = new FileReader();
+ reader.onloadend = () => setIconPreview(reader.result);
+ reader.readAsDataURL(file);
+ };
+
+ const toggleMember = (userId, userObj) => {
+ setSelectedMembers((prev) =>
+ prev.some((m) => m._id === userId)
+ ? prev.filter((m) => m._id !== userId)
+ : [...prev, userObj]
+ );
+ };
+
+ const handleSubmit = async (event) => {
+ event.preventDefault();
+ if (!name.trim()) {
+ toast.error("Group name is required");
+ return;
+ }
+
+ setIsCreating(true);
+ try {
+ const formData = new FormData();
+ formData.append("name", name.trim());
+ formData.append("memberIds", JSON.stringify(selectedMembers.map((m) => m._id)));
+ if (iconFile) formData.append("image", iconFile);
+
+ const group = await createGroup(formData);
+ if (group) {
+ closeModal();
+ onCreated?.(group);
+ }
+ } finally {
+ setIsCreating(false);
+ }
+ };
+
+ return (
+
+ );
+};
diff --git a/client/src/components/groupChatContainer.jsx b/client/src/components/groupChatContainer.jsx
new file mode 100644
index 0000000..3d65d79
--- /dev/null
+++ b/client/src/components/groupChatContainer.jsx
@@ -0,0 +1,147 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { groupStore } from "../store/groupStore.js";
+import { authStore } from "../store/authStore.js";
+import { GroupHeader } from "./groupHeader.jsx";
+import { GroupInfoModal } from "./groupInfoModal.jsx";
+import { MessageInput } from "./messageInput.jsx";
+import { MessageSkeleton } from "./skeletons/messageSkeleton.jsx";
+import { MessageBubble } from "./messageBubble.jsx";
+import { X, Loader } from "lucide-react";
+
+export default function GroupChatContainer() {
+ const [selectedImage, setSelectedImage] = useState(null);
+ const {
+ selectedGroup,
+ groupMessages,
+ isGroupMessagesLoading,
+ isFetchingMoreMessages,
+ hasMoreMessages,
+ getGroupDetails,
+ getGroupMessages,
+ loadMoreMessages,
+ sendGroupMessage,
+ isSendingGroupMessage,
+ markGroupMessagesAsSeen,
+ emitGroupTypingStart,
+ emitGroupTypingStop,
+ } = groupStore();
+ const { user } = authStore();
+
+ const messageEndRef = useRef(null);
+ const topSentinelRef = useRef(null);
+ const lastMessageIdRef = useRef(null);
+
+ useEffect(() => {
+ getGroupDetails(selectedGroup._id);
+ getGroupMessages(selectedGroup._id);
+ markGroupMessagesAsSeen(selectedGroup._id);
+ }, [selectedGroup._id, getGroupDetails, getGroupMessages, markGroupMessagesAsSeen]);
+
+ useEffect(() => {
+ const latest = groupMessages[groupMessages.length - 1];
+ if (latest && latest._id !== lastMessageIdRef.current) {
+ lastMessageIdRef.current = latest._id;
+ messageEndRef.current?.scrollIntoView({ behavior: "smooth" });
+ }
+ }, [groupMessages]);
+
+ useEffect(() => {
+ if (!hasMoreMessages) return;
+ const sentinel = topSentinelRef.current;
+ if (!sentinel) return;
+
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (entries[0].isIntersecting) loadMoreMessages();
+ },
+ { threshold: 1.0 }
+ );
+ observer.observe(sentinel);
+ return () => observer.disconnect();
+ }, [hasMoreMessages, loadMoreMessages, groupMessages.length]);
+
+ const memberNameById = useMemo(() => {
+ const map = {};
+ (selectedGroup.members || []).forEach((m) => {
+ const id = m.user?._id || m.user;
+ map[id] = m.user?.fullName || "Unknown";
+ });
+ return map;
+ }, [selectedGroup.members]);
+
+ const handleDocumentClick = useCallback((e, url) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (url) window.open(url, "_blank", "noopener,noreferrer");
+ }, []);
+
+ const handleImageClick = useCallback((message) => {
+ setSelectedImage(message);
+ }, []);
+
+ if (isGroupMessagesLoading) {
+ return (
+
+
+
+ emitGroupTypingStart(selectedGroup._id)}
+ onTypingStop={() => emitGroupTypingStop(selectedGroup._id)}
+ />
+
+ );
+ }
+
+ return (
+
+
+
+
+
+
+ {isFetchingMoreMessages && (
+
+
+
+ )}
+
+ {groupMessages.map((message) => (
+
+ ))}
+
+
+
+ {selectedImage && (
+
+
setSelectedImage(null)}
+ >
+
+
+

+
+ )}
+
+
emitGroupTypingStart(selectedGroup._id)}
+ onTypingStop={() => emitGroupTypingStop(selectedGroup._id)}
+ />
+
+ );
+}
diff --git a/client/src/components/groupHeader.jsx b/client/src/components/groupHeader.jsx
new file mode 100644
index 0000000..c082205
--- /dev/null
+++ b/client/src/components/groupHeader.jsx
@@ -0,0 +1,83 @@
+import { useMemo } from "react";
+import { X, Users, ArrowLeft } from "lucide-react";
+import { groupStore } from "../store/groupStore.js";
+import { authStore } from "../store/authStore.js";
+import { GROUP_INFO_MODAL_ID } from "./groupInfoModal.jsx";
+import { TypingIndicator } from "./typingIndicator.jsx";
+
+export const GroupHeader = () => {
+ const { selectedGroup, setSelectedGroup, typingUserIds } = groupStore();
+ const { onlineUsers, user } = authStore();
+
+ const memberNameById = useMemo(() => {
+ const map = {};
+ (selectedGroup?.members || []).forEach((m) => {
+ const id = m.user?._id || m.user;
+ map[id] = m.user?.fullName || "Someone";
+ });
+ return map;
+ }, [selectedGroup?.members]);
+
+ if (!selectedGroup) return null;
+
+ const realMembers = selectedGroup.members.filter((m) => (m.status ?? "member") === "member");
+ const onlineMemberCount = realMembers.filter((m) =>
+ onlineUsers.includes(m.user?._id || m.user)
+ ).length;
+
+ const typingNames = typingUserIds
+ .filter((id) => id !== user?._id)
+ .map((id) => memberNameById[id] || "Someone");
+
+ return (
+
+
+
+
setSelectedGroup(null)}
+ className="md:hidden shrink-0"
+ title="Back"
+ >
+
+
+
document.getElementById(GROUP_INFO_MODAL_ID)?.showModal()}
+ >
+
+
+ {selectedGroup.icon ? (
+

+ ) : (
+
+ )}
+
+
+
+
{selectedGroup.name}
+
+ {typingNames.length > 0 ? (
+
+ ) : (
+ <>
+ {realMembers.length} members
+ {onlineMemberCount > 0 ? ` · ${onlineMemberCount} online` : ""}
+ >
+ )}
+
+
+
+
+
setSelectedGroup(null)} className="hidden md:inline shrink-0">
+
+
+
+
+ );
+};
diff --git a/client/src/components/groupInfoModal.jsx b/client/src/components/groupInfoModal.jsx
new file mode 100644
index 0000000..62402a2
--- /dev/null
+++ b/client/src/components/groupInfoModal.jsx
@@ -0,0 +1,307 @@
+import { useRef, useState } from "react";
+import { X, Shield, ShieldOff, UserMinus, LogOut, UserPlus, Users, Pencil, Camera, Loader, Check } from "lucide-react";
+import { toast } from "react-toastify";
+import { groupStore } from "../store/groupStore.js";
+import { authStore } from "../store/authStore.js";
+import { MemberPicker } from "./memberPicker.jsx";
+
+export const GROUP_INFO_MODAL_ID = "group_info_modal";
+
+export const GroupInfoModal = () => {
+ const { selectedGroup, addMembers, removeMember, updateMemberRole, leaveGroup, updateGroup } =
+ groupStore();
+ const { user, onlineUsers } = authStore();
+ const [showAddMembers, setShowAddMembers] = useState(false);
+ const [newMemberIds, setNewMemberIds] = useState([]);
+
+ const [isEditing, setIsEditing] = useState(false);
+ const [editName, setEditName] = useState("");
+ const [editIconFile, setEditIconFile] = useState(null);
+ const [editIconPreview, setEditIconPreview] = useState(null);
+ const [isSavingEdit, setIsSavingEdit] = useState(false);
+ const editIconInputRef = useRef(null);
+
+ if (!selectedGroup) return null;
+
+ const myMembership = selectedGroup.members.find(
+ (m) => (m.user?._id || m.user) === user._id
+ );
+ const isAdmin = myMembership?.role === "admin";
+ const realMembers = selectedGroup.members.filter((m) => (m.status ?? "member") === "member");
+
+ const closeModal = () => {
+ document.getElementById(GROUP_INFO_MODAL_ID)?.close();
+ setShowAddMembers(false);
+ setNewMemberIds([]);
+ setIsEditing(false);
+ setEditIconFile(null);
+ setEditIconPreview(null);
+ };
+
+ const startEditing = () => {
+ setEditName(selectedGroup.name);
+ setEditIconFile(null);
+ setEditIconPreview(null);
+ setIsEditing(true);
+ };
+
+ const cancelEditing = () => {
+ setIsEditing(false);
+ setEditIconFile(null);
+ setEditIconPreview(null);
+ };
+
+ const handleEditIconChange = (event) => {
+ const file = event.target.files[0];
+ if (!file) return;
+ if (!file.type.startsWith("image/")) {
+ toast.error("Please select an image file.");
+ return;
+ }
+ setEditIconFile(file);
+ const reader = new FileReader();
+ reader.onloadend = () => setEditIconPreview(reader.result);
+ reader.readAsDataURL(file);
+ };
+
+ const handleSaveEdit = async () => {
+ if (!editName.trim()) {
+ toast.error("Group name is required");
+ return;
+ }
+ setIsSavingEdit(true);
+ try {
+ const formData = new FormData();
+ formData.append("name", editName.trim());
+ if (editIconFile) formData.append("image", editIconFile);
+ await updateGroup(selectedGroup._id, formData);
+ setIsEditing(false);
+ setEditIconFile(null);
+ setEditIconPreview(null);
+ } finally {
+ setIsSavingEdit(false);
+ }
+ };
+
+ const toggleNewMember = (userId) => {
+ setNewMemberIds((prev) =>
+ prev.includes(userId) ? prev.filter((id) => id !== userId) : [...prev, userId]
+ );
+ };
+
+ const handleAddMembers = async () => {
+ if (newMemberIds.length === 0) return;
+ await addMembers(selectedGroup._id, newMemberIds);
+ setShowAddMembers(false);
+ setNewMemberIds([]);
+ };
+
+ const handleLeave = async () => {
+ await leaveGroup(selectedGroup._id);
+ closeModal();
+ };
+
+ return (
+
+ );
+};
diff --git a/client/src/components/memberPicker.jsx b/client/src/components/memberPicker.jsx
new file mode 100644
index 0000000..8de0650
--- /dev/null
+++ b/client/src/components/memberPicker.jsx
@@ -0,0 +1,67 @@
+import { useEffect, useState } from "react";
+import { Search } from "lucide-react";
+import { groupStore } from "../store/groupStore.js";
+import { useDebounce } from "../hooks/useDebounce.js";
+
+export const MemberPicker = ({ selectedIds, onToggle, excludeIds = [] }) => {
+ const [query, setQuery] = useState("");
+ const debouncedQuery = useDebounce(query, 300);
+ const { memberSearchResults, isSearchingMembers, searchMembersForGroup, resetMemberSearch } =
+ groupStore();
+
+ useEffect(() => {
+ if (debouncedQuery.trim()) {
+ searchMembersForGroup(debouncedQuery);
+ } else {
+ resetMemberSearch();
+ }
+ }, [debouncedQuery, searchMembersForGroup, resetMemberSearch]);
+
+ const results = memberSearchResults.filter((u) => !excludeIds.includes(u._id));
+
+ return (
+
+
+
+ setQuery(e.target.value)}
+ className="w-full pl-9 px-4 py-2 border rounded-lg focus:outline-none focus:ring focus:ring-gray-300"
+ />
+
+
+
+ {isSearchingMembers &&
Searching...
}
+
+ {!isSearchingMembers && debouncedQuery.trim() && results.length === 0 && (
+
No users found
+ )}
+
+ {results.map((u) => {
+ const isChecked = selectedIds.includes(u._id);
+ return (
+
+ );
+ })}
+
+
+ );
+};
diff --git a/client/src/components/messageBubble.jsx b/client/src/components/messageBubble.jsx
new file mode 100644
index 0000000..8e35d97
--- /dev/null
+++ b/client/src/components/messageBubble.jsx
@@ -0,0 +1,111 @@
+import { memo } from "react";
+import { formatMessageTime } from "../configs/utils.js";
+import { FileText, ArrowUpRightFromSquare } from "lucide-react";
+import ReactMarkdown from "react-markdown";
+
+const formatFileSize = (bytes) => {
+ if (!bytes || bytes === 0) return "0 Bytes";
+ const k = 1024;
+ const sizes = ["Bytes", "KB", "MB", "GB"];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+ return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + " " + sizes[i];
+};
+
+const MessageBubbleComponent = ({
+ message,
+ isOwnMessage,
+ senderName,
+ onImageClick,
+ onDocumentClick,
+}) => {
+ const isGroupMessage = Boolean(message?.groupId);
+ const seenCount = isGroupMessage ? (message?.seenBy?.length ?? 0) : 0;
+
+ return (
+
+
+ {isGroupMessage && !isOwnMessage && senderName && (
+
{senderName}
+ )}
+
+ {message?.image && (
+

onImageClick?.(message)}
+ />
+ )}
+
+ {message?.document && (
+
onDocumentClick?.(e, message.document.url)}
+ >
+
+
+
+
+
+ {message.document.name || "Document"}
+
+
{formatFileSize(message.document.size)}
+
+
+
+ )}
+
+ {message.text && (
+
+ {message.text}
+
+ )}
+
+
+
+ {formatMessageTime(message?.createdAt)}
+
+
+ {isOwnMessage && (
+
+ {isGroupMessage ? (
+ seenCount > 0 ? (
+
+ ✓✓
+
+ ) : (
+ ✓
+ )
+ ) : message.seenAt ? (
+
+ ✓✓
+
+ ) : (
+ ✓
+ )}
+
+ )}
+
+
+
+ );
+};
+
+export const MessageBubble = memo(MessageBubbleComponent);
diff --git a/client/src/components/messageInput.jsx b/client/src/components/messageInput.jsx
index 1665222..14135ca 100644
--- a/client/src/components/messageInput.jsx
+++ b/client/src/components/messageInput.jsx
@@ -1,18 +1,22 @@
import { useRef, useState, useEffect } from "react";
-import { chatStore } from "../store/chatStore";
import { X, Image, Send, Loader, FileText, Paperclip } from "lucide-react";
import { toast } from "react-toastify";
-const chatBotId = "67a5af796174659ba813c735";
-
// File size limits (in MB)
const FILE_SIZE_LIMITS = {
image: 3,
document: 5,
};
-export const MessageInput = () => {
- const { sendMessage, isSendingMessage, selectedUser } = chatStore();
+const TYPING_STOP_DELAY = 2000;
+
+export const MessageInput = ({
+ onSend,
+ isSending = false,
+ hideAttachments = false,
+ onTypingStart,
+ onTypingStop,
+}) => {
const [text, setText] = useState("");
const [imageFile, setImageFile] = useState(null);
const [imagePreview, setImagePreview] = useState(null);
@@ -22,6 +26,25 @@ export const MessageInput = () => {
const imageInputRef = useRef(null);
const documentInputRef = useRef(null);
const attachMenuRef = useRef(null);
+ const typingStopTimeoutRef = useRef(null);
+
+ useEffect(() => {
+ return () => {
+ if (typingStopTimeoutRef.current) clearTimeout(typingStopTimeoutRef.current);
+ };
+ }, []);
+
+ const handleTextChange = (event) => {
+ setText(event.target.value);
+
+ if (!onTypingStart || !onTypingStop) return;
+
+ onTypingStart();
+ if (typingStopTimeoutRef.current) clearTimeout(typingStopTimeoutRef.current);
+ typingStopTimeoutRef.current = setTimeout(() => {
+ onTypingStop();
+ }, TYPING_STOP_DELAY);
+ };
useEffect(() => {
const handleClickOutside = (event) => {
@@ -110,13 +133,16 @@ export const MessageInput = () => {
event.preventDefault();
if (!text.trim() && !imageFile && !documentFile) return;
+ if (typingStopTimeoutRef.current) clearTimeout(typingStopTimeoutRef.current);
+ onTypingStop?.();
+
try {
const formData = new FormData();
if (text.trim()) formData.append("text", text.trim());
if (imageFile) formData.append("image", imageFile);
if (documentFile) formData.append("document", documentFile);
- await sendMessage(formData);
+ await onSend(formData);
setText("");
setImageFile(null);
@@ -184,7 +210,7 @@ export const MessageInput = () => {
className="w-full input input-bordered rounded-lg input-sm sm:input-md"
placeholder="Type a message..."
value={text}
- onChange={(event) => setText(event.target.value)}
+ onChange={handleTextChange}
/>
{
onChange={handleDocumentChange}
/>
- {selectedUser._id !== chatBotId && (
+ {!hideAttachments && (
{
type="submit"
className="btn btn-circle btn-sm btn-primary"
disabled={
- (!text.trim() && !imageFile && !documentFile) || isSendingMessage
+ (!text.trim() && !imageFile && !documentFile) || isSending
}
>
- {isSendingMessage ? (
+ {isSending ? (
) : (
diff --git a/client/src/components/otpInput.jsx b/client/src/components/otpInput.jsx
new file mode 100644
index 0000000..1b49405
--- /dev/null
+++ b/client/src/components/otpInput.jsx
@@ -0,0 +1,39 @@
+import { useRef } from "react";
+
+export const OtpInput = ({ value, onChange, length = 6 }) => {
+ const inputRefs = useRef([]);
+
+ const handleInputChange = (e, index) => {
+ const digit = e.target.value.slice(-1).replace(/\D/g, "");
+ const next = [...value];
+ next[index] = digit;
+ onChange(next);
+ if (digit && index < length - 1) {
+ inputRefs.current[index + 1]?.focus();
+ }
+ };
+
+ const handleKeyDown = (e, index) => {
+ if (e.key === "Backspace" && index > 0 && !value[index]) {
+ inputRefs.current[index - 1]?.focus();
+ }
+ };
+
+ return (
+
+ {Array.from({ length }).map((_, index) => (
+ handleInputChange(e, index)}
+ onKeyDown={(e) => handleKeyDown(e, index)}
+ ref={(el) => (inputRefs.current[index] = el)}
+ className="size-10 sm:size-12 text-center text-base-content text-xl rounded bg-base-200 border border-base-300"
+ />
+ ))}
+
+ );
+};
diff --git a/client/src/components/requestsTab.jsx b/client/src/components/requestsTab.jsx
new file mode 100644
index 0000000..22aed6b
--- /dev/null
+++ b/client/src/components/requestsTab.jsx
@@ -0,0 +1,125 @@
+import { useEffect } from "react";
+import { Check, X, Users } from "lucide-react";
+import { chatStore } from "../store/chatStore.js";
+import { groupStore } from "../store/groupStore.js";
+
+export const RequestsTab = () => {
+ const {
+ conversationRequests,
+ isRequestsLoading,
+ getConversationRequests,
+ acceptConversationRequest,
+ declineConversationRequest,
+ } = chatStore();
+ const {
+ pendingGroupInvites,
+ isInvitesLoading,
+ getMyGroupInvites,
+ acceptGroupInvite,
+ declineGroupInvite,
+ } = groupStore();
+
+ useEffect(() => {
+ getConversationRequests();
+ getMyGroupInvites();
+ }, [getConversationRequests, getMyGroupInvites]);
+
+ const isLoading = isRequestsLoading || isInvitesLoading;
+ const isEmpty = conversationRequests.length === 0 && pendingGroupInvites.length === 0;
+
+ if (isLoading && isEmpty) {
+ return Loading...
;
+ }
+
+ if (isEmpty) {
+ return (
+
+ No pending requests or invites
+
+ );
+ }
+
+ return (
+
+ {conversationRequests.length > 0 && (
+
+
+ Message Requests
+
+ {conversationRequests.map((req) => (
+
+

+
+
{req.peer?.fullName}
+
wants to message you
+
+
+ acceptConversationRequest(req._id)}
+ >
+
+
+ declineConversationRequest(req._id)}
+ >
+
+
+
+
+ ))}
+
+ )}
+
+ {pendingGroupInvites.length > 0 && (
+
+
+ Group Invites
+
+ {pendingGroupInvites.map((group) => (
+
+
+ {group.icon ? (
+

+ ) : (
+
+ )}
+
+
+
{group.name}
+
invited you to join
+
+
+ acceptGroupInvite(group._id)}
+ >
+
+
+ declineGroupInvite(group._id)}
+ >
+
+
+
+
+ ))}
+
+ )}
+
+ );
+};
diff --git a/client/src/components/sidebar.jsx b/client/src/components/sidebar.jsx
index 7e4cf52..650ad11 100644
--- a/client/src/components/sidebar.jsx
+++ b/client/src/components/sidebar.jsx
@@ -1,209 +1,359 @@
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { chatStore } from "../store/chatStore.js";
+import { groupStore } from "../store/groupStore.js";
import SidebarSkeleton from "./skeletons/sidebarSkeleton.jsx";
-import { Users } from "lucide-react";
+import { UsersRound, Plus, Contact } from "lucide-react";
import { authStore } from "../store/authStore.js";
-import { Search, X } from "lucide-react";
-import { toast } from "react-toastify";
-import SearchSkeleton from "./skeletons/searchSkeleton.jsx";
+import { CreateGroupModal, CREATE_GROUP_MODAL_ID } from "./createGroupModal.jsx";
+import { AllContactsModal, ALL_CONTACTS_MODAL_ID } from "./allContactsModal.jsx";
+import { RequestsTab } from "./requestsTab.jsx";
+import { loadSelection } from "../utils/selectionPersistence.js";
const chatBotId = "67a5af796174659ba813c735";
+const UnreadBadge = ({ count }) => {
+ if (!count) return null;
+ return (
+
+ {count > 9 ? "9+" : count}
+
+ );
+};
+
export default function Sidebar() {
- const [isSearchBoxOpen, setIsSearchBoxOpen] = useState(false);
- const [query, setQuery] = useState("");
+ const [activeTab, setActiveTab] = useState("chats");
+ const [showOnlineOnly, setShowOnlineOnly] = useState(false);
+ const [showUnreadOnly, setShowUnreadOnly] = useState(false);
+
const {
- users,
getUsers,
+ users,
selectedUser,
setSelectedUser,
isUsersLoading,
- getSearchResults,
- searchResults,
- resetSearchResults,
- isSearchingUser,
+ conversations,
+ isConversationsLoading,
+ getConversations,
+ conversationRequests,
+ getConversationRequests,
+ listenIncomingMessage,
+ stopListenIncomingMessage,
+ listenConversationEvents,
+ stopListenConversationEvents,
+ listenTypingEvents,
+ stopListenTypingEvents,
+ typingUserIds,
} = chatStore();
- const { onlineUsers } = authStore();
+ const {
+ myGroups,
+ getMyGroups,
+ selectedGroup,
+ setSelectedGroup,
+ isGroupsLoading,
+ listenGroupEvents,
+ stopListenGroupEvents,
+ pendingGroupInvites,
+ getMyGroupInvites,
+ } = groupStore();
- const [showOnlineOnly, setShowOnlineOnly] = useState(false);
+ const { onlineUsers, user: authUser } = authStore();
useEffect(() => {
getUsers();
}, [getUsers]);
- const filterOnlineUsers = showOnlineOnly
- ? users.filter((user) => onlineUsers.includes(user._id))
- : users;
+ useEffect(() => {
+ getConversations();
+ getConversationRequests();
+ }, [getConversations, getConversationRequests]);
- if (isUsersLoading) {
- return ;
- }
+ useEffect(() => {
+ getMyGroups();
+ getMyGroupInvites();
+ }, [getMyGroups, getMyGroupInvites]);
+
+ // Mounted once, session-wide (not scoped to an open chat/group), so the
+ // Chats/Groups/Requests lists stay live-updated no matter what's open.
+ useEffect(() => {
+ listenIncomingMessage();
+ listenConversationEvents();
+ listenTypingEvents();
+ return () => {
+ stopListenIncomingMessage();
+ stopListenConversationEvents();
+ stopListenTypingEvents();
+ };
+ }, [
+ listenIncomingMessage,
+ listenConversationEvents,
+ listenTypingEvents,
+ stopListenIncomingMessage,
+ stopListenConversationEvents,
+ stopListenTypingEvents,
+ ]);
- const handleSubmit = async (event) => {
- event.preventDefault();
- if (query.trim().length > 0) {
- await getSearchResults(query);
- } else {
- toast.warning("Atleast one character needed", {
- position: "bottom-right",
- });
+ useEffect(() => {
+ listenGroupEvents();
+ return () => stopListenGroupEvents();
+ }, [listenGroupEvents, stopListenGroupEvents]);
+
+ // Re-open whatever chat/group was open before a page refresh (selection
+ // state itself isn't persisted — it lives only in memory — so without
+ // this a refresh drops back to "no chat selected" even though every
+ // message is still there once you click back in). Keeps retrying on
+ // each data update until the saved peer/group is found (or the user
+ // makes their own selection first, which stops it).
+ const restoredSelectionRef = useRef(false);
+ useEffect(() => {
+ if (restoredSelectionRef.current) return;
+ if (selectedUser || selectedGroup) {
+ restoredSelectionRef.current = true;
+ return;
+ }
+ const saved = loadSelection(authUser?._id);
+ if (!saved) {
+ restoredSelectionRef.current = true;
+ return;
}
+ if (saved.type === "user") {
+ const peer =
+ conversations.find((c) => c.peer?._id === saved.id)?.peer ||
+ users.find((u) => u._id === saved.id);
+ if (peer) {
+ setSelectedUser(peer);
+ restoredSelectionRef.current = true;
+ }
+ } else if (saved.type === "group") {
+ const group = myGroups.find((g) => g._id === saved.id);
+ if (group) {
+ setSelectedGroup(group);
+ restoredSelectionRef.current = true;
+ }
+ }
+ }, [conversations, users, myGroups, selectedUser, selectedGroup, authUser, setSelectedUser, setSelectedGroup]);
+
+ const handleSelectUser = (user) => {
+ setSelectedGroup(null);
+ setSelectedUser(user);
+ };
+
+ const handleSelectGroup = (group) => {
+ setSelectedUser(null);
+ setSelectedGroup(group);
};
- // console.log(searchResults, "search");
+ const pendingRequestsCount = conversationRequests.length + pendingGroupInvites.length;
+
+ const visibleConversations = conversations
+ .filter((c) => !showOnlineOnly || onlineUsers.includes(c.peer?._id))
+ .filter((c) => !showUnreadOnly || c.unreadCount > 0);
+
+ const visibleGroups = myGroups.filter((g) => !showUnreadOnly || g.unreadCount > 0);
+
+ if (isUsersLoading) {
+ return ;
+ }
return (
-