diff --git a/client/package-lock.json b/client/package-lock.json index d9392d9..6bfbe04 100644 --- a/client/package-lock.json +++ b/client/package-lock.json @@ -1828,9 +1828,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001695", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001695.tgz", - "integrity": "sha512-vHyLade6wTgI2u1ec3WQBxv+2BrTERV28UXQu9LO6lZ9pYeMk34vjXFLOxo1A4UBA8XTL4njRQZdno/yYaSmWw==", + "version": "1.0.30001810", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001810.tgz", + "integrity": "sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==", "dev": true, "funding": [ { @@ -1845,7 +1845,8 @@ "type": "github", "url": "https://github.com/sponsors/ai" } - ] + ], + "license": "CC-BY-4.0" }, "node_modules/ccount": { "version": "2.0.1", diff --git a/client/src/App.jsx b/client/src/App.jsx index ef406a1..fbaafdd 100644 --- a/client/src/App.jsx +++ b/client/src/App.jsx @@ -2,6 +2,7 @@ import Navbar from "./components/navbar.jsx"; import { Routes, Route, useNavigate, Navigate } from "react-router-dom"; import RegisterPage from "./pages/register.jsx"; import LoginPage from "./pages/login.jsx"; +import ForgotPasswordPage from "./pages/forgotPassword.jsx"; import ProfilePage from "./pages/profile.jsx"; import SettingsPage from "./pages/settings.jsx"; import { authStore } from "./store/authStore.js"; @@ -21,7 +22,7 @@ function App() { if (isLoading && !user) { return ( -
+

Please Wait...

@@ -34,6 +35,10 @@ function App() { : } /> : } /> : } /> + : } + /> } /> { + const { users } = chatStore(); + const { onlineUsers } = authStore(); + const [query, setQuery] = useState(""); + + const closeModal = () => { + document.getElementById(ALL_CONTACTS_MODAL_ID)?.close(); + setQuery(""); + }; + + const filteredUsers = query.trim() + ? users.filter((u) => { + const q = query.trim().toLowerCase(); + return ( + u.fullName?.toLowerCase().includes(q) || u.email?.toLowerCase().includes(q) + ); + }) + : users; + + return ( + +
+ + +

All Contacts

+ +
+ + 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" + /> +
+ +
+ {filteredUsers.map((contact) => ( + + ))} + + {filteredUsers.length === 0 && ( +
No contacts found
+ )} +
+
+
+ +
+
+ ); +}; diff --git a/client/src/components/chat-container.jsx b/client/src/components/chat-container.jsx index 86eab7f..c103968 100644 --- a/client/src/components/chat-container.jsx +++ b/client/src/components/chat-container.jsx @@ -1,12 +1,13 @@ -import { useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { chatStore } from "../store/chatStore.js"; import { ChatHeader } from "./chatHeader.jsx"; import { MessageInput } from "./messageInput.jsx"; import { MessageSkeleton } from "./skeletons/messageSkeleton.jsx"; +import { MessageBubble } from "./messageBubble.jsx"; import { authStore } from "../store/authStore.js"; -import { formatMessageTime } from "../configs/utils.js"; -import { X, FileText, ArrowUpRightFromSquare } from "lucide-react"; -import ReactMarkdown from "react-markdown"; +import { X } from "lucide-react"; + +const chatBotId = "67a5af796174659ba813c735"; export default function ChatContainer() { const [selectedImage, setSelectedImage] = useState(null); @@ -15,9 +16,11 @@ export default function ChatContainer() { selectedUser, messages, isChatLoading, - listenIncomingMessage, - stopListenIncomingMessage, markMessagesAsSeen, + sendMessage, + isSendingMessage, + emitTypingStart, + emitTypingStop, } = chatStore(); const { user } = authStore(); @@ -25,139 +28,57 @@ export default function ChatContainer() { useEffect(() => { getMessages(selectedUser._id); - listenIncomingMessage(); markMessagesAsSeen(selectedUser._id); - return () => stopListenIncomingMessage(); - }, [ - getMessages, - selectedUser._id, - listenIncomingMessage, - stopListenIncomingMessage, - markMessagesAsSeen, - ]); + }, [getMessages, selectedUser._id, markMessagesAsSeen]); useEffect(() => { if (messageEndRef.current && messages) messageEndRef.current.scrollIntoView({ behavior: "smooth" }); }, [messages]); - const handleDocumentClick = (e, url) => { + const handleDocumentClick = useCallback((e, url) => { e.preventDefault(); e.stopPropagation(); if (url) { window.open(url, "_blank", "noopener,noreferrer"); } - }; + }, []); - 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 handleImageClick = useCallback((message) => { + setSelectedImage(message); + }, []); if (isChatLoading) { return ( -
+
- + emitTypingStart(selectedUser._id)} + onTypingStop={() => emitTypingStop(selectedUser._id)} + />
); } return ( -
+
{messages.map((message) => ( -
-
- {message?.image && ( - Attachment setSelectedImage(message)} - /> - )} - - {message?.document && ( -
handleDocumentClick(e, message.document.url)} - > -
- -
-
-

- {message.document.name || "Document"} -

-

- {formatFileSize(message.document.size)} -

-
-
- -
-
- )} - - {message.text && ( -
- {message.text} -
- )} - -
-

- {formatMessageTime(message?.createdAt)} -

- - {/* Show seen status for sent messages */} - {message?.senderId === user._id && ( - - {message.seenAt ? ( - - ✓✓ - - ) : ( - ✓ - )} - - )} -
-
-
+ message={message} + isOwnMessage={message?.senderId === user._id} + onImageClick={handleImageClick} + onDocumentClick={handleDocumentClick} + /> ))} +
{selectedImage && ( @@ -177,7 +98,13 @@ export default function ChatContainer() {
)} - + emitTypingStart(selectedUser._id)} + onTypingStop={() => emitTypingStop(selectedUser._id)} + />
); } diff --git a/client/src/components/chatHeader.jsx b/client/src/components/chatHeader.jsx index 17b429e..d6ac97b 100644 --- a/client/src/components/chatHeader.jsx +++ b/client/src/components/chatHeader.jsx @@ -1,20 +1,28 @@ -import { X } from "lucide-react"; +import { X, ArrowLeft } from "lucide-react"; import { chatStore } from "../store/chatStore.js"; import { authStore } from "../store/authStore.js"; import { useState } from "react"; +import { TypingIndicator } from "./typingIndicator.jsx"; const chatBotId = "67a5af796174659ba813c735"; export const ChatHeader = () => { const [openFullScreenImage, setOpenFullScreenImage] = useState(false); - const { selectedUser, setSelectedUser } = chatStore(); + const { selectedUser, setSelectedUser, isPeerTyping } = chatStore(); const { onlineUsers } = authStore(); return (
-
-
-
+
+
+ +
{ />
-
-

{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 ( + +
+ + +

Create Group

+ +
+
+
+
+ {iconPreview ? ( + Group icon + ) : ( + + )} +
+ + +
+
+ + setName(e.target.value)} + className="w-full input input-bordered" + maxLength={100} + /> + + {selectedMembers.length > 0 && ( +
+ {selectedMembers.map((m) => ( + toggleMember(m._id, m)} + > + {m.fullName} + + + ))} +
+ )} + + m._id)} + onToggle={toggleMember} + excludeIds={user ? [user._id] : []} + /> + +
+ + +
+ +
+
+ +
+
+ ); +}; 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 && ( +
+ + Full Screen +
+ )} + + 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 ( +
+
+
+ + +
+ +
+
+ ); +}; 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 ( + +
+ + +
+
+
+ {(isEditing ? editIconPreview : null) || selectedGroup.icon ? ( + {selectedGroup.name} + ) : ( + + )} +
+ {isEditing && ( + <> + + + + )} +
+ + {isEditing ? ( +
+ setEditName(e.target.value)} + className="w-full input input-bordered input-sm text-center" + maxLength={100} + /> +
+ + +
+
+ ) : ( +
+

{selectedGroup.name}

+ {isAdmin && ( + + )} +
+ )} +

{realMembers.length} members

+
+ + {isAdmin && ( + + )} + + {showAddMembers && ( +
+ m.user?._id || m.user)} + /> + +
+ )} + +
+ {selectedGroup.members.map((member) => { + const memberUser = member.user; + const memberUserId = memberUser?._id || memberUser; + const isOnline = onlineUsers.includes(memberUserId); + const isSelf = memberUserId === user._id; + + return ( +
+
+ {memberUser?.fullName} + {isOnline && ( + + )} +
+
+
+ + {memberUser?.fullName} {isSelf && "(You)"} + + {member.status === "invited" && ( + Pending + )} +
+
{member.role}
+
+ + {isAdmin && !isSelf && ( +
+ {member.status === "member" && ( + + )} + +
+ )} +
+ ); + })} +
+ +
+ +
+
+
+ +
+
+ ); +}; 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 && ( + Attachment 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 && (
+ +
+
+ ))} +
+ )} + + {pendingGroupInvites.length > 0 && ( +
+

+ Group Invites +

+ {pendingGroupInvites.map((group) => ( +
+
+ {group.icon ? ( + {group.name} + ) : ( + + )} +
+
+
{group.name}
+
invited you to join
+
+
+ + +
+
+ ))} +
+ )} +
+ ); +}; 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 ( -
- {filterOnlineUsers.length === 0 && ( -
No online users
- )} -
- {isSearchBoxOpen && ( -
-
{ - setIsSearchBoxOpen(false); - resetSearchResults(); - setQuery(""); - }} - /> - -
-
+ {activeTab === "chats" && ( +
- - 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" - /> - - {isSearchingUser ? : null} - -
- {searchResults && searchResults.length > 0 ? ( -
- {searchResults.map((item) => ( -
{ - setSelectedUser(item); - setIsSearchBoxOpen(false); - }} - > - {item.fullName} + )} + {activeTab === "groups" && ( + + )} +
+ + {(activeTab === "chats" || activeTab === "groups") && ( +
+ {activeTab === "chats" && ( + + )} + +
+ )} +
+ + {activeTab === "chats" && ( +
+ {isConversationsLoading ? ( +
Loading chats...
+ ) : ( + <> + {visibleConversations.map((conversation) => ( + + ))} + + {visibleConversations.length === 0 && ( +
+ + {showUnreadOnly + ? "No unread chats" + : "No chats yet. Use All Contacts or Search to start one."} +
- ) : ( -
-
- No users found + )} + + )} +
+ )} + + {activeTab === "groups" && ( +
+ {isGroupsLoading ? ( +
Loading groups...
+ ) : ( + <> + {visibleGroups.map((group) => ( + + ))} + + {visibleGroups.length === 0 && ( +
+ + {showUnreadOnly ? "No unread groups" : "No groups yet. Create one to get started."} +
)} -
-
+ + )}
)} + + {activeTab === "requests" && } + + + ); } diff --git a/client/src/components/skeletons/searchSkeleton.jsx b/client/src/components/skeletons/searchSkeleton.jsx deleted file mode 100644 index 0002996..0000000 --- a/client/src/components/skeletons/searchSkeleton.jsx +++ /dev/null @@ -1,24 +0,0 @@ -export default function SearchSkeleton() { - const skeletonContacts = Array(10).fill(null); - - return ( - - ); -} diff --git a/client/src/components/skeletons/sidebarSkeleton.jsx b/client/src/components/skeletons/sidebarSkeleton.jsx index 5332b85..9096478 100644 --- a/client/src/components/skeletons/sidebarSkeleton.jsx +++ b/client/src/components/skeletons/sidebarSkeleton.jsx @@ -6,22 +6,22 @@ export default function SidebarSkeleton() { return (