import { useState, useRef, useEffect, useCallback, memo } from 'react'; import { useConversationMessages, useDMContext } from '@/contexts/DMContext'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useAuthor } from '@/hooks/useAuthor'; import { genUserName } from '@/lib/genUserName'; import { MESSAGE_PROTOCOL, PROTOCOL_MODE, type MessageProtocol } from '@/lib/dmConstants'; import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; import { Button } from '@/components/ui/button'; import { Card } from '@/components/ui/card'; import { Textarea } from '@/components/ui/textarea'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import { ArrowLeft, Send, Loader2, AlertTriangle } from 'lucide-react'; import { cn } from '@/lib/utils'; interface DMChatAreaProps { pubkey: string | null; onBack?: () => void; className?: string; } // Helper function outside component to avoid recreation const formatMessageTime = (timestamp: number) => { const date = new Date(timestamp * 1000); return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); }; const MessageBubble = memo(({ message, isFromCurrentUser }: { message: { id: string; kind: number; decryptedContent?: string; error?: string; created_at: number; isSending?: boolean; }; isFromCurrentUser: boolean; }) => { const isNIP4Message = message.kind === 4; return (
{message.error ? (

🔒 Failed to decrypt

) : (

{message.decryptedContent}

)}
{formatMessageTime(message.created_at)} {isNIP4Message && (

Uses outdated NIP-04 encryption

)} {message.isSending && ( )}
); }); MessageBubble.displayName = 'MessageBubble'; const ChatHeader = ({ pubkey, onBack }: { pubkey: string; onBack?: () => void }) => { const author = useAuthor(pubkey); const metadata = author.data?.metadata; const displayName = metadata?.name || genUserName(pubkey); const avatarUrl = metadata?.picture; const initials = displayName.slice(0, 2).toUpperCase(); return (
{onBack && ( )} {initials}

{displayName}

{metadata?.nip05 && (

{metadata.nip05}

)}
); }; const EmptyState = ({ isLoading }: { isLoading: boolean }) => { return (
{isLoading ? ( <>

Loading conversations...

Fetching encrypted messages from relays

) : ( <>

Select a conversation to start messaging

Your messages are encrypted and stored locally

)}
); }; export const DMChatArea = ({ pubkey, onBack, className }: DMChatAreaProps) => { const { user } = useCurrentUser(); const { sendMessage, protocolMode, isLoading } = useDMContext(); const { messages } = useConversationMessages(pubkey || ''); const [messageText, setMessageText] = useState(''); const [isSending, setIsSending] = useState(false); // Determine default protocol based on mode const getDefaultProtocol = () => { if (protocolMode === PROTOCOL_MODE.NIP04_ONLY) return MESSAGE_PROTOCOL.NIP04; if (protocolMode === PROTOCOL_MODE.NIP17_ONLY) return MESSAGE_PROTOCOL.NIP17; if (protocolMode === PROTOCOL_MODE.NIP04_OR_NIP17) return MESSAGE_PROTOCOL.NIP17; // Fallback to NIP-17 for any unexpected mode return MESSAGE_PROTOCOL.NIP17; }; const [selectedProtocol, setSelectedProtocol] = useState(getDefaultProtocol()); const scrollAreaRef = useRef(null); // Determine if selection is allowed const allowSelection = protocolMode === PROTOCOL_MODE.NIP04_OR_NIP17; // Auto-scroll to bottom when new messages arrive useEffect(() => { if (scrollAreaRef.current) { const scrollContainer = scrollAreaRef.current.querySelector('[data-radix-scroll-area-viewport]'); if (scrollContainer) { scrollContainer.scrollTop = scrollContainer.scrollHeight; } } }, [messages.length]); const handleSend = useCallback(async () => { if (!messageText.trim() || !pubkey || !user) return; setIsSending(true); try { await sendMessage({ recipientPubkey: pubkey, content: messageText.trim(), protocol: selectedProtocol, }); setMessageText(''); } catch (error) { console.error('Failed to send message:', error); } finally { setIsSending(false); } }, [messageText, pubkey, user, sendMessage, selectedProtocol]); const handleKeyDown = useCallback((e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } }, [handleSend]); if (!pubkey) { return ( ); } if (!user) { return (

Please log in to view messages

); } return ( {messages.length === 0 ? (

No messages yet

Send a message to start the conversation

) : (
{messages.map((message) => ( ))}
)}