feat: Implement rich media messaging for images, files, and GIFs, and add message read/delivery status indicators.

This commit is contained in:
pradeepkumar
2026-02-21 22:11:42 +05:30
parent 3d2171e0bb
commit c5dc139633
12 changed files with 1237 additions and 118 deletions

View File

@@ -8,7 +8,7 @@ import { MessageInput } from './MessageInput';
import { useMessaging } from '@/hooks/useMessaging';
import { connectionRequestsService, type ConnectionRequest } from '@/services/connection-requests.service';
import { uploadService } from '@/services/upload.service';
import type { Conversation, Message } from '@/types/messaging';
import type { Conversation, Message, MessageType } from '@/types/messaging';
// Helper to get a valid avatar URL (must start with http://, https://, or /)
function getValidAvatarUrl(avatar: string | null | undefined): string {
@@ -110,12 +110,15 @@ export function MessagingPage() {
} = useMessaging();
const [searchQuery, setSearchQuery] = useState('');
const [isUploading, setIsUploading] = useState(false);
const [showScrollButton, setShowScrollButton] = useState(false);
const [connectedAgents, setConnectedAgents] = useState<ConnectedAgent[]>([]);
const [isLoadingAgents, setIsLoadingAgents] = useState(false);
const [isStartingConversation, setIsStartingConversation] = useState<string | null>(null);
// Store converted avatar URLs by conversation ID
const [conversationAvatarUrls, setConversationAvatarUrls] = useState<Record<string, string>>({});
// Store converted file URLs by message ID (for S3-stored images/files)
const [messageFileUrls, setMessageFileUrls] = useState<Record<string, string>>({});
const messagesContainerRef = useRef<HTMLDivElement>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const justSwitchedConversationRef = useRef(false);
@@ -246,6 +249,39 @@ export function MessagingPage() {
convertCurrentAvatar();
}, [currentConversation]);
// Convert S3 keys to presigned download URLs for message attachments
useEffect(() => {
const convertFileUrls = async () => {
for (const msg of messages) {
if ((msg.messageType === 'IMAGE' || msg.messageType === 'FILE') && msg.fileUrl) {
// Skip if already converted
if (messageFileUrls[msg.id]) continue;
// Skip if it's already an accessible URL (e.g., Giphy GIF URLs)
if (msg.fileUrl.startsWith('http://') || msg.fileUrl.startsWith('https://')) {
setMessageFileUrls(prev => ({ ...prev, [msg.id]: msg.fileUrl! }));
continue;
}
// Convert S3 key to presigned download URL
try {
const presignedUrl = await uploadService.getPresignedDownloadUrl(msg.fileUrl);
setMessageFileUrls(prev => ({ ...prev, [msg.id]: presignedUrl }));
} catch {
// Keep original if conversion fails
}
}
}
};
if (messages.length > 0) {
convertFileUrls();
}
}, [messages]);
// Clear cached file URLs when switching conversations
useEffect(() => {
setMessageFileUrls({});
}, [currentConversation?.id]);
// Handle starting a new conversation with an agent
const handleStartConversation = useCallback(async (agentProfileId: string) => {
setIsStartingConversation(agentProfileId);
@@ -265,6 +301,35 @@ export function MessagingPage() {
await sendMessage(content);
}, [sendMessage]);
// Handle sending a GIF
const handleSendGif = useCallback(async (gifUrl: string) => {
await sendMessage(gifUrl, 'IMAGE' as MessageType, { fileUrl: gifUrl, mimeType: 'image/gif' });
}, [sendMessage]);
// Handle sending a file (image or document)
const handleSendFile = useCallback(async (file: File, messageType: 'IMAGE' | 'FILE') => {
setIsUploading(true);
try {
const uploaded = await uploadService.uploadMessageFile(file);
// uploaded.url is the S3 key (not a full URL)
const content = messageType === 'IMAGE' ? 'Sent an image' : 'Sent a file';
await sendMessage(
content,
messageType as MessageType,
{
fileUrl: uploaded.url,
mimeType: file.type,
fileName: file.name,
fileSize: file.size,
}
);
} catch (error) {
console.error('Failed to upload file:', error);
} finally {
setIsUploading(false);
}
}, [sendMessage]);
// Handle typing events
const handleTypingStart = useCallback(() => {
startTyping();
@@ -599,16 +664,64 @@ export function MessagingPage() {
className={`flex ${isOwn ? 'justify-end' : 'justify-start'}`}
>
<div
className={`max-w-[70%] rounded-[15px] px-4 py-3 ${
className={`max-w-[70%] rounded-[15px] ${
message.messageType === 'IMAGE' ? 'p-1' : 'px-4 py-3'
} ${
isOwn
? 'bg-[#e58625] text-[#00293D]'
: 'bg-[#00293d]/10 text-[#00293D]'
}`}
>
<p className="font-serif font-normal text-[14px] leading-[19px]">
{message.content}
</p>
<div className={`flex items-center gap-2 mt-1 ${isOwn ? 'justify-end' : 'justify-start'}`}>
{message.messageType === 'IMAGE' ? (
messageFileUrls[message.id] ? (
<img
src={messageFileUrls[message.id]}
alt={message.fileName || 'Image'}
className="rounded-[12px] max-w-full cursor-pointer"
style={{ maxHeight: '250px' }}
onClick={() => window.open(messageFileUrls[message.id], '_blank')}
/>
) : (
<div className="w-[200px] h-[150px] rounded-[12px] bg-black/5 flex items-center justify-center">
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-[#00293d]" />
</div>
)
) : message.messageType === 'FILE' ? (
<a
href={messageFileUrls[message.id] || '#'}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-3 no-underline"
>
<div className={`w-[40px] h-[40px] rounded-[8px] flex items-center justify-center flex-shrink-0 ${isOwn ? 'bg-[#00293D]/10' : 'bg-[#e58625]/10'}`}>
<Image
src="/assets/icons/attachment-icon.svg"
alt="File"
width={20}
height={11}
/>
</div>
<div className="min-w-0">
<p className="font-serif font-medium text-[14px] leading-[19px] truncate">
{message.fileName || message.content}
</p>
{message.fileSize && (
<p className={`font-serif font-normal text-[12px] leading-[16px] ${isOwn ? 'text-[#00293D]/70' : 'text-[#00293D]/50'}`}>
{message.fileSize < 1024
? `${message.fileSize} B`
: message.fileSize < 1024 * 1024
? `${(message.fileSize / 1024).toFixed(1)} KB`
: `${(message.fileSize / (1024 * 1024)).toFixed(1)} MB`}
</p>
)}
</div>
</a>
) : (
<p className="font-serif font-normal text-[14px] leading-[19px]">
{message.content}
</p>
)}
<div className={`flex items-center gap-2 mt-1 ${message.messageType === 'IMAGE' ? 'px-2 pb-1' : ''} ${isOwn ? 'justify-end' : 'justify-start'}`}>
<p
className={`font-serif font-normal text-[12px] leading-[16px] ${
isOwn ? 'text-[#00293D]/70' : 'text-[#00293D]/50'
@@ -617,8 +730,14 @@ export function MessagingPage() {
{formatMessageTime(message.createdAt)}
</p>
{isOwn && (
<span className={`text-[10px] ${message.status === 'READ' ? 'text-blue-500' : 'text-[#00293D]/50'}`}>
{message.status === 'READ' ? '✓✓' : message.status === 'DELIVERED' ? '✓✓' : '✓'}
<span className="inline-flex items-center">
{message.status === 'READ' ? (
<Image src="/assets/icons/tick-double-blue.svg" alt="Read" width={16} height={11} />
) : message.status === 'DELIVERED' ? (
<Image src="/assets/icons/tick-double-gray.svg" alt="Delivered" width={16} height={11} />
) : (
<Image src="/assets/icons/tick-single-gray.svg" alt="Sent" width={11} height={11} />
)}
</span>
)}
</div>
@@ -669,8 +788,11 @@ export function MessagingPage() {
{/* Message input */}
<MessageInput
onSend={handleSendMessage}
onSendGif={handleSendGif}
onSendFile={handleSendFile}
onTypingStart={handleTypingStart}
onTypingStop={handleTypingStop}
isUploading={isUploading}
/>
</>
) : (