tahamajs's picture
download
raw
32.8 kB
// src/components/messages/ChatSidebar.tsx
import { useState, useMemo, useCallback, useRef, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
Search, Plus, Users, Archive, Trash2, Pin, Bell, BellOff,
Check, MoreVertical, Edit, Copy, Star, FolderPlus,
Filter, SortAsc, ArrowDown as SortDesc, Loader2, UserPlus, Settings,
Volume2, VolumeX, Shield, Flag, Ban, Eye, EyeOff
} from "lucide-react";
import { ChatItem, Conversation, Group, User } from "@/types";
import { useChatFolders } from "@/hooks/useChatFolders";
import { useWebSocket } from "@/context/WebSocketContext";
import { useAuth } from "@/context/AuthContext";
import { useContextMenu } from "@/hooks/useContextMenu";
import { ContextMenu } from "@/components/ui/ContextMenu";
import { toast } from "react-toastify";
import api from "@/lib/api";
interface Props {
chats: ChatItem[];
selectedChat: ChatItem | null;
loading: boolean;
onSelectChat: (chat: ChatItem) => void;
onDeleteChat: (chat: ChatItem) => void;
onShowProfile: (username: string) => void;
onNewChat: () => void;
contacts: any[];
onStartChatWithContact: (username: string) => void;
archivedChats: ChatItem[];
showArchive: boolean;
setShowArchive: (v: boolean) => void;
onUnarchiveChat: (chat: ChatItem) => void;
onArchiveChat: (chat: ChatItem) => void;
onPinChat?: (chat: ChatItem) => void;
onMuteChat?: (chat: ChatItem) => void;
onMarkAsRead?: (chat: ChatItem) => void;
onCreateFolder?: (name: string) => void;
onEditFolder?: (folderId: string, name: string) => void;
onDeleteFolder?: (folderId: string) => void;
onDragChatToFolder?: (chatId: string, folderId: string) => void;
}
interface TypingIndicator {
username: string;
chatId: string;
timestamp: number;
}
interface OnlineStatus {
username: string;
isOnline: boolean;
lastSeen?: string;
}
export function ChatSidebar({
chats,
selectedChat,
loading,
onSelectChat,
onDeleteChat,
onShowProfile,
onNewChat,
contacts,
onStartChatWithContact,
archivedChats,
showArchive,
setShowArchive,
onUnarchiveChat,
onArchiveChat,
onPinChat,
onMuteChat,
onMarkAsRead,
onCreateFolder,
onEditFolder,
onDeleteFolder,
onDragChatToFolder,
}: Props) {
const { user } = useAuth();
const { sendMessage, subscribe, connectionStatus } = useWebSocket();
const { folders, activeFolderId, setActiveFolderId, addChatToFolder, removeChatFromFolder } = useChatFolders();
const { contextMenu, showContextMenu, hideContextMenu } = useContextMenu();
const [searchQuery, setSearchQuery] = useState("");
const [sortBy, setSortBy] = useState<"recent" | "unread" | "name">("recent");
const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
const [showFolderMenu, setShowFolderMenu] = useState(false);
const [newFolderName, setNewFolderName] = useState("");
const [draggedChat, setDraggedChat] = useState<ChatItem | null>(null);
const [dropTargetFolder, setDropTargetFolder] = useState<string | null>(null);
const [typingIndicators, setTypingIndicators] = useState<TypingIndicator[]>([]);
const [onlineStatuses, setOnlineStatuses] = useState<Record<string, OnlineStatus>>({});
const [showCreateFolderInput, setShowCreateFolderInput] = useState(false);
const [editingFolderId, setEditingFolderId] = useState<string | null>(null);
const [editingFolderName, setEditingFolderName] = useState("");
const [showContactPicker, setShowContactPicker] = useState(false);
const [contactSearch, setContactSearch] = useState("");
const [selectedContacts, setSelectedContacts] = useState<string[]>([]);
// Subscribe to real-time events
useEffect(() => {
const unsubscribeTyping = subscribe("typing", (data) => {
setTypingIndicators(prev => {
const filtered = prev.filter(t => t.username !== data.username || t.chatId !== data.chatId);
if (data.isTyping) {
return [...filtered, { username: data.username, chatId: data.chatId, timestamp: Date.now() }];
}
return filtered;
});
});
const unsubscribeOnline = subscribe("presence", (data) => {
setOnlineStatuses(prev => ({
...prev,
[data.username]: { username: data.username, isOnline: data.isOnline, lastSeen: data.lastSeen }
}));
});
// Cleanup old typing indicators
const interval = setInterval(() => {
const now = Date.now();
setTypingIndicators(prev => prev.filter(t => now - t.timestamp < 3000));
}, 3000);
return () => {
unsubscribeTyping();
unsubscribeOnline();
clearInterval(interval);
};
}, [subscribe]);
// Filter and sort chats
const filteredAndSortedChats = useMemo(() => {
let filtered = chats.filter(chat => !chat.isArchived);
// Apply folder filter
const activeFolder = folders.find(f => f.id === activeFolderId);
if (activeFolder && activeFolder.filter) {
if (activeFolder.filter.unreadOnly) {
filtered = filtered.filter(c => (c.unread || 0) > 0);
}
if (activeFolder.filter.types?.length) {
filtered = filtered.filter(c => activeFolder.filter.types!.includes(c.type));
}
}
// Apply search
if (searchQuery) {
const q = searchQuery.toLowerCase();
filtered = filtered.filter(c => {
const name = getChatName(c);
return name.toLowerCase().includes(q);
});
}
// Apply sorting
filtered.sort((a, b) => {
let comparison = 0;
switch (sortBy) {
case "unread":
comparison = ((b.unread || 0) - (a.unread || 0));
break;
case "name":
comparison = getChatName(a).localeCompare(getChatName(b));
break;
case "recent":
default:
comparison = new Date(b.updatedAt || 0).getTime() - new Date(a.updatedAt || 0).getTime();
break;
}
return sortOrder === "asc" ? -comparison : comparison;
});
return filtered;
}, [chats, activeFolderId, folders, searchQuery, sortBy, sortOrder]);
// Get pinned chats
const pinnedChats = useMemo(() => {
return filteredAndSortedChats.filter(chat => chat.isPinned);
}, [filteredAndSortedChats]);
// Get unpinned chats
const unpinnedChats = useMemo(() => {
return filteredAndSortedChats.filter(chat => !chat.isPinned);
}, [filteredAndSortedChats]);
const getChatName = (chat: ChatItem): string => {
return chat.type === "private" ? (chat as Conversation).with : (chat as Group).name;
};
const getChatAvatar = (chat: ChatItem): string => {
if (chat.type === "group") {
return (chat as Group).avatarUrl || "";
}
return (chat as Conversation).avatarUrl || "";
};
const getLastMessage = (chat: ChatItem): string => {
const lastMsg = (chat as any).lastMessage;
if (!lastMsg) return "No messages yet";
if (lastMsg.length > 30) return lastMsg.substring(0, 30) + "...";
return lastMsg;
};
const getLastMessageTime = (chat: ChatItem): string => {
const time = (chat as any).lastMessageTime;
if (!time) return "";
const date = new Date(time);
const now = new Date();
const diff = now.getTime() - date.getTime();
const hours = diff / (1000 * 60 * 60);
if (hours < 24) {
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
if (hours < 168) {
return date.toLocaleDateString([], { weekday: 'short' });
}
return date.toLocaleDateString();
};
const isUserTyping = (chat: ChatItem): boolean => {
const chatId = getChatId(chat);
return typingIndicators.some(t => t.chatId === chatId);
};
const getChatId = (chat: ChatItem): string => {
return chat.type === "private" ? (chat as Conversation).with : `g-${(chat as Group).id}`;
};
const isUserOnline = (username: string): boolean => {
return onlineStatuses[username]?.isOnline || false;
};
const handleCreateFolder = async () => {
if (!newFolderName.trim()) return;
await onCreateFolder?.(newFolderName);
setNewFolderName("");
setShowCreateFolderInput(false);
toast.success(`Folder "${newFolderName}" created`);
};
const handleEditFolder = async (folderId: string) => {
if (!editingFolderName.trim()) return;
await onEditFolder?.(folderId, editingFolderName);
setEditingFolderId(null);
setEditingFolderName("");
toast.success("Folder renamed");
};
const handleDeleteFolder = async (folderId: string) => {
if (confirm("Delete this folder? Chats will not be deleted.")) {
await onDeleteFolder?.(folderId);
toast.success("Folder deleted");
}
};
const handleDragStart = (e: React.DragEvent, chat: ChatItem) => {
setDraggedChat(chat);
e.dataTransfer.setData("text/plain", getChatId(chat));
e.dataTransfer.effectAllowed = "move";
};
const handleDragOver = (e: React.DragEvent, folderId: string) => {
e.preventDefault();
setDropTargetFolder(folderId);
};
const handleDragLeave = () => {
setDropTargetFolder(null);
};
const handleDrop = async (e: React.DragEvent, folderId: string) => {
e.preventDefault();
if (draggedChat) {
await onDragChatToFolder?.(getChatId(draggedChat), folderId);
toast.success(`Moved to folder`);
}
setDraggedChat(null);
setDropTargetFolder(null);
};
const handleCreateGroup = async () => {
if (selectedContacts.length === 0) {
toast.error("Select at least one contact");
return;
}
try {
const response = await api.post("/groups", {
name: `Group with ${selectedContacts.join(", ")}`,
members: selectedContacts
});
toast.success("Group created");
setShowContactPicker(false);
setSelectedContacts([]);
onSelectChat(response.data);
} catch (error) {
toast.error("Failed to create group");
}
};
// Context menu for chat items
const getChatContextMenuItems = (chat: ChatItem) => [
{ label: "Mark as Read", icon: <Check className="w-4 h-4" />, onClick: () => onMarkAsRead?.(chat) },
{ label: chat.isPinned ? "Unpin Chat" : "Pin Chat", icon: <Pin className="w-4 h-4" />, onClick: () => onPinChat?.(chat) },
{ label: chat.isMuted ? "Unmute" : "Mute Notifications", icon: chat.isMuted ? <Bell className="w-4 h-4" /> : <BellOff className="w-4 h-4" />, onClick: () => onMuteChat?.(chat) },
{ divider: true },
{ label: "View Profile", icon: <Users className="w-4 h-4" />, onClick: () => onShowProfile(getChatName(chat)) },
{ label: "Search in Chat", icon: <Search className="w-4 h-4" />, onClick: () => {} },
{ divider: true },
{ label: "Add to Folder", icon: <FolderPlus className="w-4 h-4" />, onClick: () => setShowFolderMenu(true) },
{ label: "Archive Chat", icon: <Archive className="w-4 h-4" />, onClick: () => onArchiveChat(chat) },
{ divider: true },
{ label: "Delete Chat", icon: <Trash2 className="w-4 h-4" />, onClick: () => onDeleteChat(chat), danger: true },
];
// Context menu for folders
const getFolderContextMenuItems = (folder: any) => [
{ label: "Rename", icon: <Edit className="w-4 h-4" />, onClick: () => { setEditingFolderId(folder.id); setEditingFolderName(folder.name); } },
{ label: "Delete", icon: <Trash2 className="w-4 h-4" />, onClick: () => handleDeleteFolder(folder.id), danger: true },
];
// Context menu for empty area
const getEmptyAreaContextMenuItems = () => [
{ label: "New Chat", icon: <Plus className="w-4 h-4" />, onClick: onNewChat },
{ label: "Create Group", icon: <UserPlus className="w-4 h-4" />, onClick: () => setShowContactPicker(true) },
{ divider: true },
{ label: "Sort by Recent", icon: <SortDesc className="w-4 h-4" />, onClick: () => setSortBy("recent") },
{ label: "Sort by Unread", icon: <SortDesc className="w-4 h-4" />, onClick: () => setSortBy("unread") },
{ label: "Sort by Name", icon: <SortAsc className="w-4 h-4" />, onClick: () => setSortBy("name") },
];
if (loading) {
return (
<div className="w-full bg-slate-900/40 backdrop-blur-3xl border-r border-white/5 flex flex-col h-full shadow-2xl relative z-20">
<div className="p-5">
<div className="h-6 w-24 bg-slate-800 rounded animate-pulse mb-4"></div>
<div className="h-12 bg-slate-800 rounded-2xl animate-pulse shadow-inner border border-white/5"></div>
</div>
{[...Array(5)].map((_, i) => (
<div key={i} className="flex gap-4 p-4 animate-pulse border-b border-white/5">
<div className="w-12 h-12 rounded-[1.2rem] bg-slate-800 border border-white/5 shadow-inner"></div>
<div className="flex-1 py-1">
<div className="h-4 bg-slate-800 rounded w-3/4 mb-2"></div>
<div className="h-3 bg-slate-800 rounded w-1/2"></div>
</div>
</div>
))}
</div>
);
}
return (
<div
className="w-full bg-transparent flex flex-col h-full"
onContextMenu={(e) => showContextMenu(e, getEmptyAreaContextMenuItems())}
>
{/* Header */}
<div className="px-5 py-4 border-b border-white/5 relative">
<div className="flex justify-between items-center mb-4">
<h2 className="text-xl font-black bg-gradient-to-r from-slate-100 to-indigo-300 bg-clip-text text-transparent tracking-wide">
Network
{connectionStatus !== "connected" && (
<span className="ml-2 text-xs text-amber-500 animate-pulse">●</span>
)}
</h2>
<div className="flex gap-2">
<button
onClick={onNewChat}
className="p-2.5 rounded-[1rem] bg-indigo-500/10 text-indigo-400 hover:bg-indigo-500/20 hover:text-indigo-300 border border-indigo-500/20 transition-all shadow-inner hover:shadow-[0_0_15px_rgba(99,102,241,0.2)]"
title="New Chat"
>
<Plus className="w-4 h-4" />
</button>
<button
onClick={() => setShowContactPicker(true)}
className="p-2.5 rounded-[1rem] bg-indigo-500/10 text-indigo-400 hover:bg-indigo-500/20 hover:text-indigo-300 border border-indigo-500/20 transition-all shadow-inner hover:shadow-[0_0_15px_rgba(99,102,241,0.2)]"
title="Create Group"
>
<UserPlus className="w-4 h-4" />
</button>
</div>
</div>
{/* Search */}
<div className="relative group">
<Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-500 group-focus-within:text-indigo-400 transition-colors" />
<input
type="text"
placeholder="Search network..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full pl-10 pr-4 py-3 bg-slate-950/60 border border-white/5 text-white placeholder-slate-500 rounded-[1.2rem] text-sm focus:outline-none focus:border-indigo-500/50 shadow-inner transition-all"
/>
</div>
</div>
{/* Sort options */}
<div className="px-4 py-3 flex gap-2 overflow-x-auto border-b border-white/5 scrollbar-hide">
<button
onClick={() => setSortBy("recent")}
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-colors shadow-sm ${sortBy === "recent" ? "bg-indigo-600 text-white" : "bg-slate-900 border border-white/5 text-slate-400 hover:text-white"}`}
>
Recent
</button>
<button
onClick={() => setSortBy("unread")}
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-colors shadow-sm ${sortBy === "unread" ? "bg-indigo-600 text-white" : "bg-slate-900 border border-white/5 text-slate-400 hover:text-white"}`}
>
Unread
</button>
<button
onClick={() => setSortBy("name")}
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-colors shadow-sm ${sortBy === "name" ? "bg-indigo-600 text-white" : "bg-slate-900 border border-white/5 text-slate-400 hover:text-white"}`}
>
Name
</button>
<button
onClick={() => setSortOrder(prev => prev === "asc" ? "desc" : "asc")}
className="px-3 py-1.5 rounded-xl text-xs font-bold bg-slate-900 border border-white/5 text-slate-400 hover:text-white shadow-sm transition-colors flex items-center justify-center"
>
{sortOrder === "asc" ? <SortAsc className="w-3.5 h-3.5" /> : <SortDesc className="w-3.5 h-3.5" />}
</button>
</div>
{/* Custom Folders */}
{folders.length > 0 && (
<div className="px-4 py-3 flex gap-2 overflow-x-auto border-b border-white/5 scrollbar-hide">
<button
onClick={() => setActiveFolderId("all")}
className={`px-4 py-1.5 rounded-xl text-xs font-bold whitespace-nowrap transition-all shadow-sm ${
activeFolderId === "all"
? "bg-gradient-to-r from-indigo-500 to-purple-500 text-white border border-transparent shadow-[0_0_15px_rgba(99,102,241,0.3)]"
: "bg-slate-900 border border-white/5 text-slate-400 hover:text-white hover:bg-slate-800"
}`}
>
All Chats
</button>
{folders.map((f) => (
<div
key={f.id}
className="relative"
onDragOver={(e) => handleDragOver(e, f.id)}
onDragLeave={handleDragLeave}
onDrop={(e) => handleDrop(e, f.id)}
>
<button
onClick={() => setActiveFolderId(f.id)}
onContextMenu={(e) => showContextMenu(e, getFolderContextMenuItems(f))}
className={`px-4 py-1.5 rounded-xl text-xs font-bold whitespace-nowrap transition-all shadow-sm flex items-center gap-1.5 ${
activeFolderId === f.id
? "bg-gradient-to-r from-indigo-500 to-purple-500 text-white border border-transparent shadow-[0_0_15px_rgba(99,102,241,0.3)]"
: "bg-slate-900 border border-white/5 text-slate-400 hover:text-white hover:bg-slate-800"
} ${dropTargetFolder === f.id ? "ring-2 ring-indigo-500 bg-indigo-500/20" : ""}`}
>
{f.icon} {f.name}
</button>
{editingFolderId === f.id && (
<input
type="text"
value={editingFolderName}
onChange={(e) => setEditingFolderName(e.target.value)}
onBlur={() => handleEditFolder(f.id)}
onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) => e.key === "Enter" && handleEditFolder(f.id)}
className="absolute top-0 left-0 w-full px-3 py-1.5 text-xs rounded-xl border border-indigo-500 bg-slate-900 text-white outline-none"
autoFocus
/>
)}
</div>
))}
<button
onClick={() => setShowCreateFolderInput(true)}
className="px-3 py-1.5 rounded-xl text-xs font-bold bg-slate-900 border border-white/5 text-slate-400 hover:text-white transition-colors flex items-center gap-1"
>
<FolderPlus className="w-3.5 h-3.5" /> New
</button>
</div>
)}
{/* Create Folder Input */}
{showCreateFolderInput && (
<div className="px-3 py-2">
<div className="flex gap-2">
<input
type="text"
value={newFolderName}
onChange={(e) => setNewFolderName(e.target.value)}
placeholder="Folder name"
className="flex-1 px-2 py-1 text-sm border rounded-lg"
autoFocus
onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) => e.key === "Enter" && handleCreateFolder()}
/>
<button onClick={handleCreateFolder} className="px-2 py-1 bg-primary text-white rounded text-sm">Add</button>
<button onClick={() => setShowCreateFolderInput(false)} className="px-2 py-1 border rounded text-sm">Cancel</button>
</div>
</div>
)}
{/* Archive toggle */}
{archivedChats.length > 0 && (
<div className="px-3 py-2">
<button
onClick={() => setShowArchive(!showArchive)}
className={`w-full flex items-center gap-2 px-3 py-2 rounded-xl text-sm transition ${
showArchive ? "bg-primary/10 text-primary" : "hover:bg-white/30"
}`}
>
<Archive className="w-4 h-4" />
Archived Chats
<span className="ml-auto text-xs">{archivedChats.length}</span>
</button>
</div>
)}
{/* Archived List */}
<AnimatePresence>
{showArchive && archivedChats.length > 0 && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: "auto", opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
className="border-b border-white/20 dark:border-gray-800/20 overflow-hidden"
>
<div className="px-3 py-1 text-xs text-gray-400 uppercase">Archive</div>
{archivedChats.map((chat) => {
const name = getChatName(chat);
return (
<div
key={`archive-${getChatId(chat)}`}
className="flex items-center gap-2 px-3 py-2 hover:bg-white/30 group"
onContextMenu={(e) => showContextMenu(e, getChatContextMenuItems(chat))}
>
<div className="w-8 h-8 rounded-full bg-gradient-to-br from-gray-400 to-gray-500 flex items-center justify-center text-white text-xs font-bold">
{chat.type === "group" ? <Users className="w-4 h-4" /> : name[0]?.toUpperCase()}
</div>
<div className="flex-1 min-w-0">
<p className="text-sm truncate">{name}</p>
<p className="text-xs text-gray-400 truncate">{getLastMessage(chat)}</p>
</div>
<button
onClick={() => onUnarchiveChat(chat)}
className="text-xs text-primary opacity-0 group-hover:opacity-100 transition"
>
Unarchive
</button>
</div>
);
})}
</motion.div>
)}
</AnimatePresence>
{/* Main Chat List */}
<div className="flex-1 overflow-y-auto scrollbar-hide pb-6">
{filteredAndSortedChats.length === 0 ? (
<div className="p-8 text-center text-slate-500 h-full flex flex-col items-center justify-center">
<div className="w-20 h-20 rounded-3xl bg-slate-900 border border-white/5 flex items-center justify-center shadow-inner mb-4">
<Users className="w-8 h-8 text-indigo-500/50" />
</div>
<p className="font-bold text-slate-300">No active channels</p>
<p className="mt-2 text-xs text-slate-500">Initiate a secure connection or join a decentralized hub to begin.</p>
<button onClick={onNewChat} className="mt-6 px-6 py-2.5 rounded-xl bg-indigo-600 text-white text-xs font-bold hover:bg-indigo-500 shadow-[0_0_15px_rgba(99,102,241,0.3)] transition-all">
Initialize Connection
</button>
</div>
) : (
<>
{/* Pinned Chats */}
{pinnedChats.length > 0 && (
<div className="mb-2">
<div className="px-5 py-3 text-[10px] font-black tracking-widest text-indigo-400 uppercase">Pinned Contacts</div>
{pinnedChats.map((chat) => (
<ChatItemComponent
key={`pinned-${getChatId(chat)}`}
chat={chat}
selectedChat={selectedChat}
onSelectChat={onSelectChat}
onShowProfile={onShowProfile}
onArchiveChat={onArchiveChat}
onContextMenu={(e: React.MouseEvent<HTMLDivElement>) => showContextMenu(e, getChatContextMenuItems(chat))}
onDragStart={(e: React.DragEvent<HTMLDivElement>) => handleDragStart(e, chat)}
getChatName={getChatName}
getLastMessage={getLastMessage}
getLastMessageTime={getLastMessageTime}
isUserTyping={isUserTyping(chat)}
isUserOnline={chat.type === "private" ? isUserOnline(getChatName(chat)) : false}
/>
))}
</div>
)}
{/* Unpinned Chats */}
{unpinnedChats.length > 0 && (
<div>
{pinnedChats.length > 0 && <div className="px-5 py-3 text-[10px] font-black tracking-widest text-slate-500 uppercase mt-2 border-t border-white/5">Active Network</div>}
{unpinnedChats.map((chat) => (
<ChatItemComponent
key={`chat-${getChatId(chat)}`}
chat={chat}
selectedChat={selectedChat}
onSelectChat={onSelectChat}
onShowProfile={onShowProfile}
onArchiveChat={onArchiveChat}
onContextMenu={(e: React.MouseEvent<HTMLDivElement>) => showContextMenu(e, getChatContextMenuItems(chat))}
onDragStart={(e: React.DragEvent<HTMLDivElement>) => handleDragStart(e, chat)}
getChatName={getChatName}
getLastMessage={getLastMessage}
getLastMessageTime={getLastMessageTime}
isUserTyping={isUserTyping(chat)}
isUserOnline={chat.type === "private" ? isUserOnline(getChatName(chat)) : false}
/>
))}
</div>
)}
</>
)}
</div>
{/* Contact Picker Modal for Group Creation */}
{showContactPicker && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50" onClick={() => setShowContactPicker(false)}>
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-md w-full p-6" onClick={(e: React.MouseEvent<HTMLDivElement>) => e.stopPropagation()}>
<h2 className="text-xl font-bold mb-4">Create New Group</h2>
<input
type="text"
placeholder="Search contacts..."
value={contactSearch}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setContactSearch(e.target.value)}
className="w-full px-3 py-2 border rounded-lg mb-3"
/>
<div className="max-h-64 overflow-y-auto mb-4">
{contacts
.filter(c => c.username.toLowerCase().includes(contactSearch.toLowerCase()))
.map(contact => (
<label key={contact.username} className="flex items-center gap-3 p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded cursor-pointer">
<input
type="checkbox"
checked={selectedContacts.includes(contact.username)}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.checked) {
setSelectedContacts([...selectedContacts, contact.username]);
} else {
setSelectedContacts(selectedContacts.filter(u => u !== contact.username));
}
}}
className="rounded"
/>
<div className="w-8 h-8 rounded-full bg-gradient-to-br from-primary to-secondary text-white flex items-center justify-center text-sm">
{contact.username[0]?.toUpperCase()}
</div>
<div>
<div className="font-medium">{contact.fullName || contact.username}</div>
<div className="text-xs text-gray-500">@{contact.username}</div>
</div>
</label>
))}
</div>
<div className="flex gap-3">
<button onClick={() => setShowContactPicker(false)} className="flex-1 px-4 py-2 border rounded-lg">Cancel</button>
<button onClick={handleCreateGroup} className="flex-1 px-4 py-2 bg-primary text-white rounded-lg">Create Group</button>
</div>
</div>
</div>
)}
{/* Context Menu */}
<ContextMenu
items={contextMenu.items}
position={contextMenu.position}
onClose={hideContextMenu}
/>
</div>
);
}
// Separate component for each chat item to improve performance
function ChatItemComponent({
chat,
selectedChat,
onSelectChat,
onShowProfile,
onArchiveChat,
onContextMenu,
onDragStart,
getChatName,
getLastMessage,
getLastMessageTime,
isUserTyping,
isUserOnline,
}: any) {
const name = getChatName(chat);
const isGroup = chat.type === "group";
const isSelected = selectedChat === chat;
const unread = chat.unread || 0;
return (
<motion.div
draggable
onDragStart={onDragStart}
onClick={() => onSelectChat(chat)}
onContextMenu={onContextMenu}
className={`px-4 py-3.5 cursor-pointer flex items-center gap-4 transition-all duration-300 relative group overflow-hidden ${
isSelected
? "bg-slate-800/80 shadow-[inset_4px_0_0_0_rgba(99,102,241,1)]"
: "hover:bg-slate-800/40"
}`}
>
{isSelected && <div className="absolute inset-0 bg-gradient-to-r from-indigo-500/10 to-transparent pointer-events-none" />}
{/* Avatar */}
<div
onClick={(e: React.MouseEvent<HTMLDivElement>) => {
e.stopPropagation();
if (!isGroup) onShowProfile(name);
}}
className="relative w-12 h-12 flex-shrink-0"
>
<div className="w-full h-full rounded-[1.2rem] bg-gradient-to-br from-indigo-500/20 to-purple-500/20 border border-indigo-500/30 text-indigo-300 flex items-center justify-center font-black text-lg shadow-inner cursor-pointer group-hover:scale-105 transition-transform duration-300">
{isGroup ? <Users className="w-5 h-5" /> : name[0]?.toUpperCase()}
</div>
{!isGroup && isUserOnline && (
<div className="absolute -bottom-1 -right-1 flex h-4 w-4 items-center justify-center rounded-full bg-slate-900 border-2 border-slate-900">
<span className="h-2.5 w-2.5 rounded-full bg-emerald-500 animate-pulse"></span>
</div>
)}
</div>
{/* Chat Info */}
<div className="flex-1 min-w-0 relative z-10">
<div className="flex justify-between items-center mb-1">
<span className={`font-bold truncate text-sm transition-colors ${isSelected ? "text-indigo-300" : "text-white group-hover:text-indigo-200"}`}>{name}</span>
<span className={`text-[10px] font-bold uppercase tracking-wider flex-shrink-0 ml-2 ${isSelected ? "text-indigo-400" : "text-slate-500"}`}>
{getLastMessageTime(chat)}
</span>
</div>
<div className="flex items-center gap-1.5">
{isUserTyping ? (
<span className="text-xs font-bold text-indigo-400 animate-pulse">Typing...</span>
) : (
<p className={`text-xs truncate ${unread > 0 ? "text-white font-medium" : "text-slate-400"}`}>{getLastMessage(chat)}</p>
)}
{unread > 0 && (
<span className="bg-gradient-to-r from-indigo-500 to-purple-500 text-white px-1.5 py-0.5 rounded-md text-[10px] font-black ml-auto flex-shrink-0 shadow-[0_0_10px_rgba(99,102,241,0.4)]">
{unread > 99 ? "99+" : unread}
</span>
)}
{chat.isMuted && (
<BellOff className="w-3.5 h-3.5 text-slate-600 ml-1 flex-shrink-0" />
)}
{chat.isPinned && (
<Pin className="w-3.5 h-3.5 text-indigo-500 ml-1 flex-shrink-0 transform rotate-45" />
)}
</div>
</div>
{/* Archive button on hover */}
<button
onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
e.stopPropagation();
onArchiveChat(chat);
}}
className="opacity-0 group-hover:opacity-100 transition-all p-2 rounded-xl hover:bg-slate-700 bg-slate-900/80 border border-white/5 shadow-lg absolute right-4 z-20"
>
<Archive className="w-4 h-4 text-slate-400 hover:text-white transition-colors" />
</button>
</motion.div>
);
}

Xet Storage Details

Size:
32.8 kB
·
Xet hash:
4e1c1a20ab1c83704f0ed2eee87001acd44c053fed748f7c1b7b3410852028d7

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.