added the p2p and group with the fetch data from jwt token

This commit is contained in:
sumona-banerjeee committed 2026-04-17 12:36:59 +05:30
1 parent 6fa6415bfa
commit 04128f0205
6 files changed
+526 -198

No files matched your search

+388 -128
View File
@@ -4,7 +4,7 @@ import { useState, useEffect, useRef, useMemo } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/context/AuthContext";
import { useSocket, type ChatMessage, type RoomNotice } from "@/context/SocketContext";
import { fetchConversations, createConversation } from "@/lib/api";
import { fetchConversations, createConversation, fetchAllUsers, ConversationType, addParticipant, removeParticipant } from "@/lib/api";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import {
@@ -18,6 +18,9 @@ import {
Wifi,
WifiOff,
Users,
User as UserIcon,
UserMinus,
UserPlus,
} from "lucide-react";
import {
Avatar,
@@ -26,22 +29,17 @@ import {
} from "@/components/ui/avatar";
import { useDebounce } from "@/hooks/useDebounce";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface Room {
id: string;
name: string;
isGroup: boolean;
participants: { _id: string; name: string }[];
}
/* ------------------------------------------------------------------ */
/* Backend rooms loaded dynamically */
/* ------------------------------------------------------------------ */
/* ------------------------------------------------------------------ */
/* ChatPage */
/* ------------------------------------------------------------------ */
export default function ChatPage() {
const router = useRouter();
const { user, isLoading: authLoading, logout } = useAuth();
@@ -51,71 +49,143 @@ export default function ChatPage() {
joinRoom,
leaveRoom,
sendMessage,
startP2P,
messages,
notices,
currentRoom,
setCurrentRoom,
clearMessages,
p2pReady,
clearP2PReady,
} = useSocket();
const [text, setText] = useState("");
const [search, setSearch] = useState("");
const [activeTab, setActiveTab] = useState<"rooms" | "create">("rooms");
const [roomSearch, setRoomSearch] = useState("");
const [userSearch, setUserSearch] = useState("");
const [activeTab, setActiveTab] = useState<"rooms" | "users" | "create">("rooms");
const [newRoomName, setNewRoomName] = useState("");
const [rooms, setRooms] = useState<Room[]>([]);
const [allUsers, setAllUsers] = useState<any[]>([]);
const debouncedSearch = useDebounce(search, 300);
const debouncedRoomSearch = useDebounce(roomSearch, 300);
const debouncedUserSearch = useDebounce(userSearch, 300);
const messagesEndRef = useRef<HTMLDivElement>(null);
const [managingRoom, setManagingRoom] = useState<Room | null>(null);
// ── Auth guard ────────────────────────────────────────────────────
// Auth guard
useEffect(() => {
if (!authLoading && !user) {
router.push("/login");
}
}, [authLoading, user, router]);
// ── Fetch rooms & Auto-join ─────────────────────────────────────
// Fetch rooms & Auto-join
useEffect(() => {
if (!isConnected) return;
// Fetch conversations from API
fetchConversations()
// Guard: wait for everything needed
if (!isConnected || !user?.userId || allUsers.length === 0) return;
fetchConversations(user.userId)
.then((data) => {
// Map backend returned data to Room format
const loadedRooms = Array.isArray(data) ? data.map(c => ({
id: c._id || c.id || "unknown",
name: c.name || "Unnamed Group",
isGroup: c.type === "group" || c.isGroup || true
})) : [];
const loadedRooms = Array.isArray(data)
? data.map((c) => {
const isGroup = c.type === "group";
let roomName = c.name;
// FIX: derive name for P2P
if (!isGroup) {
let otherUserName = "Unknown User";
// Case 1: participants are objects
if (typeof c.participants?.[0] === "object") {
const otherUser = c.participants.find(
(p: any) => p._id !== user.userId
);
otherUserName = otherUser?.name || otherUserName;
}
// Case 2: participants are IDs
else {
const otherUserId = c.participants?.find(
(id: string) => id !== user.userId
);
const otherUser = allUsers.find(
(u) => u._id === otherUserId
);
otherUserName = otherUser?.name || otherUserName;
}
roomName = otherUserName;
}
return {
id: c._id || c.id,
name: roomName || "Unnamed Group",
isGroup,
participants: c.participants || [],
};
})
: [];
setRooms(loadedRooms);
// Auto-join first room
// Auto-join first room (only once)
if (!currentRoom && loadedRooms.length > 0) {
const firstRoom = loadedRooms[0];
setCurrentRoom(firstRoom.id);
joinRoom(firstRoom.id);
}
})
.catch(err => {
console.error("Failed to fetch conversations", err);
.catch((err) => {
console.error("Failed to fetch conversations", err.message);
});
}, [isConnected, currentRoom, joinRoom, setCurrentRoom]);
}, [isConnected, user, allUsers, currentRoom, joinRoom, setCurrentRoom]);
// ── Scroll to bottom on new messages ──────────────────────────────
// Fetch all users for P2P tab
useEffect(() => {
if (!user) return;
fetchAllUsers()
.then((data) => {
if (Array.isArray(data)) {
setAllUsers(data.filter((u: any) => u.name !== user.username));
}
})
.catch(console.error);
}, [user]);
// ── React to P2P Ready event
useEffect(() => {
if (!p2pReady) return;
const targetUser = allUsers.find((u) => u._id === p2pReady.targetUserId);
const roomName = targetUser?.name || "Direct Message";
// Add the new P2P room to sidebar if not already there
setRooms((prev) => {
if (prev.find((r) => r.id === p2pReady.roomId)) return prev;
return [...prev, { id: p2pReady.roomId, name: roomName, isGroup: false }];
});
// Switch to rooms tab
setActiveTab("rooms");
clearP2PReady();
}, [p2pReady, allUsers, clearP2PReady]);
// ── Scroll to bottom on new messages
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages, notices]);
// ── Filtered rooms ────────────────────────────────────────────────
// ── Filtered rooms
const filteredRooms = useMemo(() => {
if (!debouncedSearch.trim()) return rooms;
if (!debouncedRoomSearch.trim()) return rooms;
return rooms.filter((r) =>
r.name.toLowerCase().includes(debouncedSearch.toLowerCase())
r.name.toLowerCase().includes(debouncedRoomSearch.toLowerCase())
);
}, [rooms, debouncedSearch]);
}, [rooms, debouncedRoomSearch]);
// ── Messages for current room ─────────────────────────────────────
// ── Messages for current room
const roomMessages = useMemo(
() => messages.filter((m) => m.roomId === currentRoom),
[messages, currentRoom]
@@ -126,7 +196,7 @@ export default function ChatPage() {
[notices, currentRoom]
);
// ── Handlers ──────────────────────────────────────────────────────
// ── Handlers
const handleSelectRoom = (room: Room) => {
if (currentRoom === room.id) return;
@@ -155,20 +225,20 @@ export default function ChatPage() {
const handleCreateRoom = async () => {
const name = newRoomName.trim();
if (!name) return;
console.log(user);
try {
// Actually create the room on the backend
const created = await createConversation({ name, type: "group", participants: [user?.username || "unknown"] });
const newRoom: Room = {
id: created._id || created.id || name.toLowerCase().replace(/\s+/g, "-"),
name: created.name || name,
isGroup: true
};
setRooms((prev) => {
if (prev.find((r) => r.id === newRoom.id)) return prev;
return [...prev, newRoom];
const created = await createConversation({
name,
type: ConversationType.GROUP,
participants: [user!.userId], // send userId not username
});
const newRoom: Room = {
id: created._id || created.id,
name: created.name || name,
isGroup: true,
participants: created.participants || [],
};
setRooms(prev => prev.find(r => r.id === newRoom.id) ? prev : [...prev, newRoom]);
setNewRoomName("");
setActiveTab("rooms");
handleSelectRoom(newRoom);
@@ -177,6 +247,42 @@ export default function ChatPage() {
}
};
const handleAddParticipant = async (convId: string, userId: string) => {
try {
const updated = await addParticipant(convId, userId);
setRooms(prev => prev.map(r =>
r.id === convId
? { ...r, participants: updated.participants || r.participants }
: r
));
// refresh managingRoom state
setManagingRoom(prev => prev?.id === convId ? { ...prev, participants: updated.participants || prev.participants } : prev);
} catch (err: any) {
console.error("Add participant failed:", err.message);
}
};
const handleRemoveParticipant = async (convId: string, userId: string) => {
try {
const updated = await removeParticipant(convId, userId);
setRooms(prev => prev.map(r =>
r.id === convId
? { ...r, participants: updated.participants || r.participants }
: r
));
setManagingRoom(prev => prev?.id === convId ? { ...prev, participants: updated.participants || prev.participants } : prev);
} catch (err: any) {
console.error("Remove participant failed:", err.message);
}
};
const handleStartP2P = (targetUser: any) => {
if (!targetUser?._id) return;
startP2P(targetUser._id);
};
const handleLogout = () => {
if (currentRoom) leaveRoom(currentRoom);
clearMessages();
@@ -237,26 +343,33 @@ export default function ChatPage() {
</div>
{/* TABS */}
<div className="flex gap-6 px-4 text-sm font-medium border-b pb-2">
<div className="flex gap-4 px-4 text-sm font-medium border-b pb-2">
<button
onClick={() => setActiveTab("rooms")}
className={`pb-1 ${
activeTab === "rooms"
? "text-primary border-b-2 border-primary"
: "text-muted-foreground"
}`}
className={`pb-1 ${activeTab === "rooms"
? "text-primary border-b-2 border-primary"
: "text-muted-foreground"
}`}
>
Rooms
Chats
</button>
<button
onClick={() => setActiveTab("users")}
className={`pb-1 ${activeTab === "users"
? "text-primary border-b-2 border-primary"
: "text-muted-foreground"
}`}
>
People
</button>
<button
onClick={() => setActiveTab("create")}
className={`pb-1 ${
activeTab === "create"
? "text-primary border-b-2 border-primary"
: "text-muted-foreground"
}`}
className={`pb-1 ${activeTab === "create"
? "text-primary border-b-2 border-primary"
: "text-muted-foreground"
}`}
>
Create
Group
</button>
</div>
@@ -281,64 +394,213 @@ export default function ChatPage() {
</div>
)}
{/* SEARCH */}
<div className="p-4">
<Input
placeholder="Search rooms..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="rounded-full bg-muted"
/>
</div>
{/* ROOM LIST */}
<div className="flex-1 overflow-y-auto px-2 space-y-1">
{filteredRooms.length === 0 && (
<p className="p-4 text-sm text-muted-foreground">
No rooms found
</p>
)}
{activeTab === "rooms" && (
<div className="flex flex-col flex-1 min-h-0">
<div className="p-4">
<Input
placeholder="Search rooms..."
value={roomSearch}
onChange={(e) => setRoomSearch(e.target.value)}
className="rounded-full bg-muted"
/>
</div>
<div className="flex-1 overflow-y-auto px-2 space-y-1">
{filteredRooms.length === 0 && (
<p className="p-4 text-sm text-muted-foreground">
No conversations yet. Start a chat from People tab!
</p>
)}
{filteredRooms.map((room) => {
const isActive = currentRoom === room.id;
const unreadCount = messages.filter(
(m) => m.roomId === room.id && m.senderId !== mySocketId
).length;
{filteredRooms.map((room) => {
const isActive = currentRoom === room.id;
return (
<div
key={room.id}
onClick={() => handleSelectRoom(room)}
className={`flex items-center gap-3 p-3 rounded-xl cursor-pointer transition
${
isActive
? "bg-primary text-primary-foreground"
: "hover:bg-muted"
}
`}
>
<div
className={`w-10 h-10 flex items-center justify-center rounded-full ${
isActive ? "bg-white/20" : "bg-primary/10"
}`}
>
{room.isGroup ? (
<Users className={`w-5 h-5 ${isActive ? "text-white" : "text-primary"}`} />
) : (
<Hash className={`w-5 h-5 ${isActive ? "text-white" : "text-primary"}`} />
)}
</div>
return (
<div key={room.id} className="flex items-center gap-1 pr-2">
<div
onClick={() => handleSelectRoom(room)}
className={`flex items-center gap-3 p-3 rounded-xl cursor-pointer transition flex-1 min-w-0
${isActive
? "bg-primary text-primary-foreground"
: "hover:bg-muted"
}`}
>
<div
className={`w-10 h-10 flex-shrink-0 flex items-center justify-center rounded-full ${isActive ? "bg-white/20" : "bg-primary/10"
}`}
>
{room.isGroup ? (
<Users className={`w-5 h-5 ${isActive ? "text-white" : "text-primary"}`} />
) : (
<UserIcon className={`w-5 h-5 ${isActive ? "text-white" : "text-primary"}`} />
)}
</div>
<div className="flex-1 overflow-hidden">
<h3 className="font-semibold truncate">{room.name}</h3>
<p className="text-xs opacity-70 truncate">
#{room.id}
<div className="flex-1 overflow-hidden">
<h3 className="font-semibold truncate">{room.name}</h3>
<p className="text-xs opacity-70 truncate">
{room.isGroup ? `${room.participants?.length ?? 0} members` : "Direct Message"}
</p>
</div>
</div>
{/* Manage button — group rooms only */}
{room.isGroup && (
<button
onClick={() =>
setManagingRoom(managingRoom?.id === room.id ? null : room)
}
className={`flex-shrink-0 p-2 rounded-lg transition ${managingRoom?.id === room.id
? "bg-primary/10 text-primary"
: "text-muted-foreground hover:bg-muted"
}`}
title="Manage participants"
>
<Users className="w-4 h-4" />
</button>
)}
</div>
);
})}
</div>
{/* ── Manage participants panel ── */}
{managingRoom && (
<div className="border-t mx-2 mb-2 rounded-xl bg-muted/40 p-3 space-y-3 max-h-72 overflow-y-auto">
<div className="flex items-center justify-between">
<p className="text-xs font-semibold truncate">
{managingRoom.name}
</p>
<button
onClick={() => setManagingRoom(null)}
className="text-xs text-muted-foreground hover:text-foreground"
>
✕
</button>
</div>
{/* Current members */}
<div className="space-y-1">
<p className="text-xs text-muted-foreground uppercase tracking-wide">
Members ({managingRoom.participants?.length ?? 0})
</p>
{(managingRoom.participants ?? []).map((p: any) => {
const pid = p._id ?? p;
const pname = p.name ?? pid;
const isSelf = pid === user?.userId;
return (
<div
key={pid}
className="flex items-center justify-between gap-2 py-1"
>
<div className="flex items-center gap-2 min-w-0">
<div className="w-7 h-7 flex-shrink-0 flex items-center justify-center rounded-full bg-primary/10">
<UserIcon className="w-3.5 h-3.5 text-primary" />
</div>
<span className="text-sm truncate">
{pname}
{isSelf && (
<span className="text-muted-foreground text-xs ml-1">(you)</span>
)}
</span>
</div>
{!isSelf && (
<button
onClick={() => handleRemoveParticipant(managingRoom.id, pid)}
className="flex-shrink-0 p-1 rounded-md text-destructive hover:bg-destructive/10 transition"
title={`Remove ${pname}`}
>
<UserMinus className="w-3.5 h-3.5" />
</button>
)}
</div>
);
})}
</div>
{/* Add people */}
{(() => {
const addable = allUsers.filter(
(u) =>
!(managingRoom.participants ?? []).some(
(p: any) => (p._id ?? p) === u._id
)
);
if (addable.length === 0) return null;
return (
<div className="space-y-1">
<p className="text-xs text-muted-foreground uppercase tracking-wide">
Add people
</p>
{addable.map((u) => (
<div
key={u._id}
className="flex items-center justify-between gap-2 py-1"
>
<div className="flex items-center gap-2 min-w-0">
<div className="w-7 h-7 flex-shrink-0 flex items-center justify-center rounded-full bg-primary/10">
<UserIcon className="w-3.5 h-3.5 text-primary" />
</div>
<span className="text-sm truncate">{u.name}</span>
</div>
<button
onClick={() => handleAddParticipant(managingRoom.id, u._id)}
className="flex-shrink-0 p-1 rounded-md text-primary hover:bg-primary/10 transition"
title={`Add ${u.name}`}
>
<UserPlus className="w-3.5 h-3.5" />
</button>
</div>
))}
</div>
);
})()}
</div>
);
})}
</div>
)}
</div>
)}
{/* USERS / PEOPLE LIST (for starting P2P) */}
{activeTab === "users" && (
<div className="flex flex-col flex-1 min-h-0">
<div className="p-4">
<Input
placeholder="Search people..."
value={userSearch}
onChange={(e) => setUserSearch(e.target.value)}
className="rounded-full bg-muted"
/>
</div>
<div className="flex-1 overflow-y-auto px-2 space-y-1">
{allUsers.length === 0 ? (
<p className="p-4 text-sm text-muted-foreground">
No other users found.
</p>
) : (
allUsers
.filter((u) =>
!debouncedUserSearch.trim() ||
u.name?.toLowerCase().includes(debouncedUserSearch.toLowerCase())
)
.map((u) => (
<div
key={u._id}
onClick={() => handleStartP2P(u)}
className="flex items-center gap-3 p-3 rounded-xl cursor-pointer transition hover:bg-muted"
>
<div className="w-10 h-10 flex items-center justify-center rounded-full bg-primary/10">
<UserIcon className="w-5 h-5 text-primary" />
</div>
<div className="flex-1 overflow-hidden">
<h3 className="font-semibold truncate">{u.name}</h3>
<p className="text-xs opacity-70 truncate">Click to chat</p>
</div>
</div>
))
)}
</div>
</div>
)}
</div>
{/* ================= RIGHT CHAT ================= */}
@@ -347,13 +609,20 @@ export default function ChatPage() {
<div className="p-4 border-b font-semibold flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-10 h-10 flex items-center justify-center rounded-full bg-primary/10">
<Users className="w-5 h-5 text-primary" />
{selectedRoom?.isGroup ? (
<Users className="w-5 h-5 text-primary" />
) : (
<UserIcon className="w-5 h-5 text-primary" />
)}
</div>
<div>
<span className="text-lg">{selectedRoom?.name || "Select a room"}</span>
{selectedRoom && (
<p className="text-xs text-muted-foreground font-normal">
#{selectedRoom.id} · {isConnected ? "Connected" : "Disconnected"}
{selectedRoom.isGroup
? `${selectedRoom.participants?.length ?? 0} members`
: "Direct Message"}{" "}
· {isConnected ? "Connected" : "Disconnected"}
</p>
)}
</div>
@@ -392,28 +661,22 @@ export default function ChatPage() {
</div>
)}
{/* Interleave messages and notices by order */}
{roomMessages.map((msg, idx) => {
const isMe = msg.senderId === mySocketId;
return (
<div
key={`msg-${idx}`}
className={`flex ${isMe ? "justify-end" : "justify-start"}`}
>
<div className="flex flex-col max-w-xs">
{/* Show sender name for others */}
{!isMe && (
<span className="text-xs text-muted-foreground mb-1 ml-1">
{msg.username}
</span>
)}
<div
className={`px-4 py-2 rounded-xl ${
isMe
? "bg-primary text-primary-foreground"
: "bg-muted"
}`}
className={`px-4 py-2 rounded-xl ${isMe ? "bg-primary text-primary-foreground" : "bg-muted"
}`}
>
{msg.text}
</div>
@@ -422,7 +685,6 @@ export default function ChatPage() {
);
})}
{/* Room notices */}
{roomNotices.map((notice, idx) => (
<div key={`notice-${idx}`} className="flex justify-center">
<span className="text-xs text-muted-foreground bg-muted/50 px-3 py-1 rounded-full">
@@ -441,9 +703,7 @@ export default function ChatPage() {
onChange={(e) => setText(e.target.value)}
onKeyDown={handleKeyDown}
placeholder={
currentRoom
? `Message #${currentRoom}...`
: "Select a room first..."
currentRoom ? `Message ${selectedRoom?.name ?? ""}...` : "Select a room first..."
}
disabled={!currentRoom || !isConnected}
/>