added the date time and proper conversation history
This commit is contained in:
1 parent
04128f0205
commit
d2ea0ff9cb
3 files changed
+432
-334
No files matched your search
+395
-280
@@ -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, fetchAllUsers, ConversationType, addParticipant, removeParticipant } from "@/lib/api";
|
||||
import { fetchConversations, createConversation, fetchAllUsers, ConversationType, addParticipant, removeParticipant, fetchMessages } from "@/lib/api";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -14,23 +14,12 @@ import {
|
||||
Plus,
|
||||
LogOut,
|
||||
Loader2,
|
||||
Hash,
|
||||
Wifi,
|
||||
WifiOff,
|
||||
Users,
|
||||
User as UserIcon,
|
||||
UserMinus,
|
||||
UserPlus,
|
||||
ChevronDown,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
Avatar,
|
||||
AvatarFallback,
|
||||
AvatarImage,
|
||||
} from "@/components/ui/avatar";
|
||||
import { useDebounce } from "@/hooks/useDebounce";
|
||||
|
||||
|
||||
|
||||
|
||||
interface Room {
|
||||
id: string;
|
||||
@@ -39,7 +28,6 @@ interface Room {
|
||||
participants: { _id: string; name: string }[];
|
||||
}
|
||||
|
||||
|
||||
export default function ChatPage() {
|
||||
const router = useRouter();
|
||||
const { user, isLoading: authLoading, logout } = useAuth();
|
||||
@@ -56,21 +44,36 @@ export default function ChatPage() {
|
||||
setCurrentRoom,
|
||||
clearMessages,
|
||||
p2pReady,
|
||||
setMessages,
|
||||
clearP2PReady,
|
||||
} = useSocket();
|
||||
|
||||
const [text, setText] = useState("");
|
||||
const [roomSearch, setRoomSearch] = useState("");
|
||||
const [userSearch, setUserSearch] = useState("");
|
||||
const [activeTab, setActiveTab] = useState<"rooms" | "users" | "create">("rooms");
|
||||
const [activeTab, setActiveTab] = useState<"rooms" | "users">("rooms");
|
||||
const [showCreateDropdown, setShowCreateDropdown] = useState(false);
|
||||
const [newRoomName, setNewRoomName] = useState("");
|
||||
const [rooms, setRooms] = useState<Room[]>([]);
|
||||
const [allUsers, setAllUsers] = useState<any[]>([]);
|
||||
const [showManageDropdown, setShowManageDropdown] = useState(false);
|
||||
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||
const manageDropdownRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Debounce helper
|
||||
const useDebounce = (value: string, delay: number) => {
|
||||
const [debounced, setDebounced] = useState(value);
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => setDebounced(value), delay);
|
||||
return () => clearTimeout(t);
|
||||
}, [value, delay]);
|
||||
return debounced;
|
||||
};
|
||||
|
||||
const debouncedRoomSearch = useDebounce(roomSearch, 300);
|
||||
const debouncedUserSearch = useDebounce(userSearch, 300);
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const [managingRoom, setManagingRoom] = useState<Room | null>(null);
|
||||
|
||||
// Auth guard
|
||||
useEffect(() => {
|
||||
@@ -81,7 +84,6 @@ export default function ChatPage() {
|
||||
|
||||
// Fetch rooms & Auto-join
|
||||
useEffect(() => {
|
||||
// Guard: wait for everything needed
|
||||
if (!isConnected || !user?.userId || allUsers.length === 0) return;
|
||||
|
||||
fetchConversations(user.userId)
|
||||
@@ -89,33 +91,22 @@ export default function ChatPage() {
|
||||
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 {
|
||||
} else {
|
||||
const otherUserId = c.participants?.find(
|
||||
(id: string) => id !== user.userId
|
||||
);
|
||||
|
||||
const otherUser = allUsers.find(
|
||||
(u) => u._id === otherUserId
|
||||
);
|
||||
|
||||
const otherUser = allUsers.find((u) => u._id === otherUserId);
|
||||
otherUserName = otherUser?.name || otherUserName;
|
||||
}
|
||||
|
||||
roomName = otherUserName;
|
||||
}
|
||||
|
||||
@@ -130,7 +121,6 @@ export default function ChatPage() {
|
||||
|
||||
setRooms(loadedRooms);
|
||||
|
||||
// Auto-join first room (only once)
|
||||
if (!currentRoom && loadedRooms.length > 0) {
|
||||
const firstRoom = loadedRooms[0];
|
||||
setCurrentRoom(firstRoom.id);
|
||||
@@ -142,7 +132,40 @@ export default function ChatPage() {
|
||||
});
|
||||
}, [isConnected, user, allUsers, currentRoom, joinRoom, setCurrentRoom]);
|
||||
|
||||
// Fetch all users for P2P tab
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
if (!currentRoom) return;
|
||||
|
||||
fetchMessages(currentRoom)
|
||||
.then((data) => {
|
||||
const normalized = data.map((msg: any) => ({
|
||||
_id: msg._id,
|
||||
roomId: msg.conversationId,
|
||||
senderId: msg.senderId._id,
|
||||
username: msg.senderId.name,
|
||||
text: msg.text,
|
||||
createdAt: msg.createdAt,
|
||||
}));
|
||||
|
||||
// Replace only this room's messages
|
||||
setMessages((prev) => {
|
||||
const others = prev.filter((m) => m.roomId !== currentRoom);
|
||||
return [...others, ...normalized];
|
||||
});
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error("Failed to fetch messages:", err);
|
||||
});
|
||||
}, [currentRoom, setMessages]);
|
||||
|
||||
|
||||
|
||||
|
||||
// Fetch all users
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
fetchAllUsers()
|
||||
@@ -154,30 +177,52 @@ export default function ChatPage() {
|
||||
.catch(console.error);
|
||||
}, [user]);
|
||||
|
||||
// ── React to P2P Ready event
|
||||
// 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 }];
|
||||
return [
|
||||
...prev,
|
||||
{ id: p2pReady.roomId, name: roomName, isGroup: false, participants: [] },
|
||||
];
|
||||
});
|
||||
|
||||
// Switch to rooms tab
|
||||
setActiveTab("rooms");
|
||||
clearP2PReady();
|
||||
}, [p2pReady, allUsers, clearP2PReady]);
|
||||
|
||||
// ── Scroll to bottom on new messages
|
||||
// Scroll to bottom on new messages
|
||||
useEffect(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
}, [messages, notices]);
|
||||
|
||||
// ── Filtered rooms
|
||||
// Close create dropdown on outside click
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (e: MouseEvent) => {
|
||||
if (!dropdownRef.current) return;
|
||||
if (dropdownRef.current.contains(e.target as Node)) return;
|
||||
setShowCreateDropdown(false);
|
||||
};
|
||||
document.addEventListener("click", handleClickOutside);
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||
}, []);
|
||||
|
||||
// Close manage dropdown on outside click
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (e: MouseEvent) => {
|
||||
if (!manageDropdownRef.current) return;
|
||||
if (manageDropdownRef.current.contains(e.target as Node)) return;
|
||||
setShowManageDropdown(false);
|
||||
};
|
||||
document.addEventListener("click", handleClickOutside);
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||
}, []);
|
||||
|
||||
// Filtered rooms
|
||||
const filteredRooms = useMemo(() => {
|
||||
if (!debouncedRoomSearch.trim()) return rooms;
|
||||
return rooms.filter((r) =>
|
||||
@@ -185,7 +230,7 @@ export default function ChatPage() {
|
||||
);
|
||||
}, [rooms, debouncedRoomSearch]);
|
||||
|
||||
// ── Messages for current room
|
||||
// Messages for current room
|
||||
const roomMessages = useMemo(
|
||||
() => messages.filter((m) => m.roomId === currentRoom),
|
||||
[messages, currentRoom]
|
||||
@@ -196,17 +241,13 @@ export default function ChatPage() {
|
||||
[notices, currentRoom]
|
||||
);
|
||||
|
||||
// ── Handlers
|
||||
// Handlers
|
||||
const handleSelectRoom = (room: Room) => {
|
||||
if (currentRoom === room.id) return;
|
||||
|
||||
// Leave old room
|
||||
if (currentRoom) {
|
||||
leaveRoom(currentRoom);
|
||||
}
|
||||
// Join new room
|
||||
if (currentRoom) leaveRoom(currentRoom);
|
||||
setCurrentRoom(room.id);
|
||||
joinRoom(room.id);
|
||||
setShowManageDropdown(false);
|
||||
};
|
||||
|
||||
const handleSend = () => {
|
||||
@@ -225,12 +266,11 @@ export default function ChatPage() {
|
||||
const handleCreateRoom = async () => {
|
||||
const name = newRoomName.trim();
|
||||
if (!name) return;
|
||||
console.log(user);
|
||||
try {
|
||||
const created = await createConversation({
|
||||
name,
|
||||
type: ConversationType.GROUP,
|
||||
participants: [user!.userId], // send userId not username
|
||||
participants: [user!.userId],
|
||||
});
|
||||
const newRoom: Room = {
|
||||
id: created._id || created.id,
|
||||
@@ -238,8 +278,11 @@ export default function ChatPage() {
|
||||
isGroup: true,
|
||||
participants: created.participants || [],
|
||||
};
|
||||
setRooms(prev => prev.find(r => r.id === newRoom.id) ? prev : [...prev, newRoom]);
|
||||
setRooms((prev) =>
|
||||
prev.find((r) => r.id === newRoom.id) ? prev : [...prev, newRoom]
|
||||
);
|
||||
setNewRoomName("");
|
||||
setShowCreateDropdown(false);
|
||||
setActiveTab("rooms");
|
||||
handleSelectRoom(newRoom);
|
||||
} catch (err) {
|
||||
@@ -247,17 +290,30 @@ 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);
|
||||
|
||||
// Normalize participants: if they're plain ID strings, hydrate with names from allUsers
|
||||
const rawParticipants: any[] = updated.participants || [];
|
||||
const hydrated = rawParticipants.map((p: any) => {
|
||||
if (typeof p === "string") {
|
||||
const found = allUsers.find((u) => u._id === p);
|
||||
return found ? { _id: found._id, name: found.name } : { _id: p, name: p };
|
||||
}
|
||||
// Already an object — but name might be missing, try to fill it in
|
||||
if (!p.name) {
|
||||
const found = allUsers.find((u) => u._id === (p._id ?? p));
|
||||
return found ? { _id: found._id, name: found.name } : p;
|
||||
}
|
||||
return p;
|
||||
});
|
||||
|
||||
setRooms((prev) =>
|
||||
prev.map((r) =>
|
||||
r.id === convId ? { ...r, participants: hydrated } : r
|
||||
)
|
||||
);
|
||||
} catch (err: any) {
|
||||
console.error("Add participant failed:", err.message);
|
||||
}
|
||||
@@ -266,18 +322,53 @@ export default function ChatPage() {
|
||||
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);
|
||||
|
||||
const rawParticipants: any[] = updated.participants || [];
|
||||
const hydrated = rawParticipants.map((p: any) => {
|
||||
if (typeof p === "string") {
|
||||
const found = allUsers.find((u) => u._id === p);
|
||||
return found ? { _id: found._id, name: found.name } : { _id: p, name: p };
|
||||
}
|
||||
if (!p.name) {
|
||||
const found = allUsers.find((u) => u._id === (p._id ?? p));
|
||||
return found ? { _id: found._id, name: found.name } : p;
|
||||
}
|
||||
return p;
|
||||
});
|
||||
|
||||
setRooms((prev) =>
|
||||
prev.map((r) =>
|
||||
r.id === convId ? { ...r, participants: hydrated } : r
|
||||
)
|
||||
);
|
||||
} catch (err: any) {
|
||||
console.error("Remove participant failed:", err.message);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const formatDate = (dateStr: string) => {
|
||||
const date = new Date(dateStr);
|
||||
const today = new Date();
|
||||
|
||||
const isToday = date.toDateString() === today.toDateString();
|
||||
if (isToday) return "Today";
|
||||
|
||||
return date.toLocaleDateString([], {
|
||||
day: "numeric",
|
||||
month: "short",
|
||||
year: "numeric",
|
||||
});
|
||||
};
|
||||
|
||||
const formatTime = (dateStr: string) => {
|
||||
const date = new Date(dateStr);
|
||||
return date.toLocaleTimeString([], {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
};
|
||||
|
||||
const handleStartP2P = (targetUser: any) => {
|
||||
if (!targetUser?._id) return;
|
||||
startP2P(targetUser._id);
|
||||
@@ -289,7 +380,7 @@ export default function ChatPage() {
|
||||
logout();
|
||||
};
|
||||
|
||||
// ── Loading / Auth guard ──────────────────────────────────────────
|
||||
// Loading / Auth guard
|
||||
if (authLoading || !user) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-background">
|
||||
@@ -300,6 +391,12 @@ export default function ChatPage() {
|
||||
|
||||
const selectedRoom = rooms.find((r) => r.id === currentRoom);
|
||||
|
||||
// Participants for manage dropdown (current selected group room)
|
||||
const manageParticipants = selectedRoom?.participants ?? [];
|
||||
const addableUsers = allUsers.filter(
|
||||
(u) => !manageParticipants.some((p: any) => (p._id ?? p) === u._id)
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex h-screen">
|
||||
{/* ================= LEFT SIDEBAR ================= */}
|
||||
@@ -308,23 +405,44 @@ export default function ChatPage() {
|
||||
<div className="flex items-center justify-between p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<h2 className="text-xl font-semibold">Chats</h2>
|
||||
{/* Connection indicator */}
|
||||
{isConnected ? (
|
||||
<Wifi className="w-4 h-4 text-green-500" />
|
||||
) : (
|
||||
<WifiOff className="w-4 h-4 text-red-500" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="rounded-full"
|
||||
onClick={() => setActiveTab(activeTab === "create" ? "rooms" : "create")}
|
||||
title="Create room"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</Button>
|
||||
{/* Create Group Dropdown */}
|
||||
<div className="relative" ref={dropdownRef}>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="rounded-full"
|
||||
onClick={() => setShowCreateDropdown((prev) => !prev)}
|
||||
title="Create group"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</Button>
|
||||
|
||||
{showCreateDropdown && (
|
||||
<div className="absolute right-0 mt-2 w-64 bg-background border rounded-xl shadow-lg p-3 space-y-2 z-50">
|
||||
<Input
|
||||
placeholder="Room name..."
|
||||
value={newRoomName}
|
||||
onChange={(e) => setNewRoomName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") handleCreateRoom();
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
<Button
|
||||
onClick={handleCreateRoom}
|
||||
disabled={!newRoomName.trim()}
|
||||
className="w-full"
|
||||
>
|
||||
Create Group
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Logout */}
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
@@ -339,10 +457,11 @@ export default function ChatPage() {
|
||||
|
||||
{/* USER INFO */}
|
||||
<div className="px-4 pb-2 text-sm text-muted-foreground">
|
||||
Logged in as <span className="font-medium text-foreground">{user.username}</span>
|
||||
Logged in as{" "}
|
||||
<span className="font-medium text-foreground">{user.username}</span>
|
||||
</div>
|
||||
|
||||
{/* TABS */}
|
||||
{/* TABS — only Chats & People */}
|
||||
<div className="flex gap-4 px-4 text-sm font-medium border-b pb-2">
|
||||
<button
|
||||
onClick={() => setActiveTab("rooms")}
|
||||
@@ -362,38 +481,8 @@ export default function ChatPage() {
|
||||
>
|
||||
People
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab("create")}
|
||||
className={`pb-1 ${activeTab === "create"
|
||||
? "text-primary border-b-2 border-primary"
|
||||
: "text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
Group
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* CREATE ROOM PANEL */}
|
||||
{activeTab === "create" && (
|
||||
<div className="p-4 space-y-3 border-b">
|
||||
<Input
|
||||
placeholder="Room name..."
|
||||
value={newRoomName}
|
||||
onChange={(e) => setNewRoomName(e.target.value)}
|
||||
className="rounded-full bg-muted"
|
||||
onKeyDown={(e) => e.key === "Enter" && handleCreateRoom()}
|
||||
/>
|
||||
<Button
|
||||
onClick={handleCreateRoom}
|
||||
disabled={!newRoomName.trim()}
|
||||
className="w-full rounded-full"
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Create Room
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ROOM LIST */}
|
||||
{activeTab === "rooms" && (
|
||||
<div className="flex flex-col flex-1 min-h-0">
|
||||
@@ -414,153 +503,43 @@ export default function ChatPage() {
|
||||
|
||||
{filteredRooms.map((room) => {
|
||||
const isActive = currentRoom === room.id;
|
||||
|
||||
return (
|
||||
<div key={room.id} className="flex items-center gap-1 pr-2">
|
||||
<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
|
||||
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"
|
||||
className={`w-10 h-10 flex-shrink-0 flex items-center justify-center rounded-full ${isActive ? "bg-white/20" : "bg-primary/10"
|
||||
}`}
|
||||
>
|
||||
<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.isGroup ? `${room.participants?.length ?? 0} members` : "Direct Message"}
|
||||
</p>
|
||||
</div>
|
||||
{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.isGroup
|
||||
? `${room.participants?.length ?? 0} members`
|
||||
: "Direct Message"}
|
||||
</p>
|
||||
</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>
|
||||
)}
|
||||
|
||||
{/* USERS / PEOPLE LIST (for starting P2P) */}
|
||||
{/* PEOPLE LIST */}
|
||||
{activeTab === "users" && (
|
||||
<div className="flex flex-col flex-1 min-h-0">
|
||||
<div className="p-4">
|
||||
@@ -578,9 +557,12 @@ export default function ChatPage() {
|
||||
</p>
|
||||
) : (
|
||||
allUsers
|
||||
.filter((u) =>
|
||||
!debouncedUserSearch.trim() ||
|
||||
u.name?.toLowerCase().includes(debouncedUserSearch.toLowerCase())
|
||||
.filter(
|
||||
(u) =>
|
||||
!debouncedUserSearch.trim() ||
|
||||
u.name
|
||||
?.toLowerCase()
|
||||
.includes(debouncedUserSearch.toLowerCase())
|
||||
)
|
||||
.map((u) => (
|
||||
<div
|
||||
@@ -593,7 +575,9 @@ export default function ChatPage() {
|
||||
</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>
|
||||
<p className="text-xs opacity-70 truncate">
|
||||
Click to chat
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
@@ -616,7 +600,9 @@ export default function ChatPage() {
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-lg">{selectedRoom?.name || "Select a room"}</span>
|
||||
<span className="text-lg">
|
||||
{selectedRoom?.name || "Select a room"}
|
||||
</span>
|
||||
{selectedRoom && (
|
||||
<p className="text-xs text-muted-foreground font-normal">
|
||||
{selectedRoom.isGroup
|
||||
@@ -628,7 +614,7 @@ export default function ChatPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Call Buttons */}
|
||||
{/* Right-side action buttons */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
@@ -644,6 +630,103 @@ export default function ChatPage() {
|
||||
>
|
||||
<Video className="w-5 h-5" />
|
||||
</Button>
|
||||
|
||||
{/* Manage Participants — only for group rooms */}
|
||||
{selectedRoom?.isGroup && (
|
||||
<div className="relative" ref={manageDropdownRef}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setShowManageDropdown((prev) => !prev)}
|
||||
title="Manage participants"
|
||||
className={showManageDropdown ? "bg-muted" : ""}
|
||||
>
|
||||
<UserPlus className="w-5 h-5" />
|
||||
</Button>
|
||||
|
||||
{showManageDropdown && (
|
||||
<div className="absolute right-0 mt-2 w-72 bg-background border rounded-xl shadow-lg p-3 space-y-3 z-50 max-h-80 overflow-y-auto">
|
||||
<p className="text-sm font-semibold truncate">
|
||||
{selectedRoom.name}
|
||||
</p>
|
||||
|
||||
{/* Current members */}
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs text-muted-foreground uppercase tracking-wide">
|
||||
Members ({manageParticipants.length})
|
||||
</p>
|
||||
{manageParticipants.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(selectedRoom.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 */}
|
||||
{addableUsers.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs text-muted-foreground uppercase tracking-wide">
|
||||
Add people
|
||||
</p>
|
||||
{addableUsers.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(selectedRoom.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>
|
||||
</div>
|
||||
|
||||
@@ -655,35 +738,65 @@ export default function ChatPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{currentRoom && roomMessages.length === 0 && roomNotices.length === 0 && (
|
||||
<div className="flex items-center justify-center h-full text-muted-foreground">
|
||||
No messages yet. Say something!
|
||||
</div>
|
||||
)}
|
||||
{currentRoom &&
|
||||
roomMessages.length === 0 &&
|
||||
roomNotices.length === 0 && (
|
||||
<div className="flex items-center justify-center h-full text-muted-foreground">
|
||||
No messages yet. Say something!
|
||||
</div>
|
||||
)}
|
||||
|
||||
{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">
|
||||
{!isMe && (
|
||||
<span className="text-xs text-muted-foreground mb-1 ml-1">
|
||||
{msg.username}
|
||||
</span>
|
||||
{(() => {
|
||||
let lastDate = "";
|
||||
|
||||
return roomMessages.map((msg, idx) => {
|
||||
const msgDate = formatDate(msg.createdAt!);
|
||||
const showDate = msgDate !== lastDate;
|
||||
lastDate = msgDate;
|
||||
|
||||
const isMe =
|
||||
msg.senderId === user?.userId ||
|
||||
msg.senderId === mySocketId;
|
||||
|
||||
return (
|
||||
<div key={msg._id || idx}>
|
||||
{/* DATE SEPARATOR */}
|
||||
{showDate && (
|
||||
<div className="flex justify-center my-4">
|
||||
<span className="text-xs bg-muted px-3 py-1 rounded-full text-muted-foreground">
|
||||
{msgDate}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className={`px-4 py-2 rounded-xl ${isMe ? "bg-primary text-primary-foreground" : "bg-muted"
|
||||
}`}
|
||||
>
|
||||
{msg.text}
|
||||
|
||||
{/* MESSAGE */}
|
||||
<div className={`flex ${isMe ? "justify-end" : "justify-start"}`}>
|
||||
<div className="flex flex-col max-w-xs">
|
||||
{!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"
|
||||
}`}
|
||||
>
|
||||
<div>{msg.text}</div>
|
||||
|
||||
{/* TIME */}
|
||||
<div className="text-[10px] text-right opacity-70 mt-1">
|
||||
{formatTime(msg.createdAt!)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
);
|
||||
});
|
||||
})()}
|
||||
|
||||
{roomNotices.map((notice, idx) => (
|
||||
<div key={`notice-${idx}`} className="flex justify-center">
|
||||
@@ -703,7 +816,9 @@ export default function ChatPage() {
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder={
|
||||
currentRoom ? `Message ${selectedRoom?.name ?? ""}...` : "Select a room first..."
|
||||
currentRoom
|
||||
? `Message ${selectedRoom?.name ?? ""}...`
|
||||
: "Select a room first..."
|
||||
}
|
||||
disabled={!currentRoom || !isConnected}
|
||||
/>
|
||||
|
||||
Reference in new issue
Block a user