import { useState, useEffect, useRef, useCallback } from 'react'; import Message from './Message.jsx'; import MessageInput from './MessageInput.jsx'; import { api } from '../utils/api.js'; import { useAuth } from '../contexts/AuthContext.jsx'; import { useToast } from '../contexts/ToastContext.jsx'; import { useSocket } from '../contexts/SocketContext.jsx'; import './ChatWindow.css'; import GroupInfoModal from './GroupInfoModal.jsx'; export default function ChatWindow({ group, onBack, onGroupUpdated, onDirectMessage, onlineUserIds = new Set() }) { const { user: currentUser } = useAuth(); const { socket } = useSocket(); const { toast } = useToast(); const [messages, setMessages] = useState([]); const [loading, setLoading] = useState(false); const [hasMore, setHasMore] = useState(false); const [typing, setTyping] = useState([]); const [iconGroupInfo, setIconGroupInfo] = useState(''); const [avatarColors, setAvatarColors] = useState({ public: '#1a73e8', dm: '#a142f4' }); const [showInfo, setShowInfo] = useState(false); const [replyTo, setReplyTo] = useState(null); const [isMobile, setIsMobile] = useState(window.innerWidth < 768); const messagesEndRef = useRef(null); const messagesContainerRef = useRef(null); const typingTimers = useRef({}); useEffect(() => { const onResize = () => setIsMobile(window.innerWidth < 768); window.addEventListener('resize', onResize); return () => window.removeEventListener('resize', onResize); }, []); useEffect(() => { api.getSettings().then(({ settings }) => { setIconGroupInfo(settings.icon_groupinfo || ''); setAvatarColors({ public: settings.color_avatar_public || '#1a73e8', dm: settings.color_avatar_dm || '#a142f4' }); }).catch(() => {}); const handler = () => api.getSettings().then(({ settings }) => { setIconGroupInfo(settings.icon_groupinfo || ''); setAvatarColors({ public: settings.color_avatar_public || '#1a73e8', dm: settings.color_avatar_dm || '#a142f4' }); }).catch(() => {}); window.addEventListener('jama:settings-updated', handler); window.addEventListener('jama:settings-changed', handler); return () => { window.removeEventListener('jama:settings-updated', handler); window.removeEventListener('jama:settings-changed', handler); }; }, []); const scrollToBottom = useCallback((smooth = false) => { messagesEndRef.current?.scrollIntoView({ behavior: smooth ? 'smooth' : 'auto' }); }, []); useEffect(() => { if (!group) { setMessages([]); return; } setMessages([]); setHasMore(false); setLoading(true); api.getMessages(group.id) .then(({ messages }) => { setMessages(messages); setHasMore(messages.length >= 50); setTimeout(() => scrollToBottom(), 50); }) .catch(e => toast(e.message, 'error')) .finally(() => setLoading(false)); }, [group?.id]); // Socket events useEffect(() => { if (!socket || !group) return; const handleNew = (msg) => { if (msg.group_id !== group.id) return; setMessages(prev => { if (prev.find(m => m.id === msg.id)) return prev; return [...prev, msg]; }); setTimeout(() => scrollToBottom(true), 50); }; const handleDeleted = ({ messageId }) => { setMessages(prev => prev.map(m => m.id === messageId ? { ...m, is_deleted: 1, content: null, image_url: null } : m )); }; const handleReaction = ({ messageId, reactions }) => { setMessages(prev => prev.map(m => m.id === messageId ? { ...m, reactions } : m )); }; const handleTypingStart = ({ userId: tid, user: tu }) => { if (tid === currentUser?.id) return; setTyping(prev => prev.find(t => t.userId === tid) ? prev : [...prev, { userId: tid, name: tu?.display_name || tu?.name || 'Someone' }]); if (typingTimers.current[tid]) clearTimeout(typingTimers.current[tid]); typingTimers.current[tid] = setTimeout(() => { setTyping(prev => prev.filter(t => t.userId !== tid)); }, 4000); }; const handleTypingStop = ({ userId: tid }) => { clearTimeout(typingTimers.current[tid]); setTyping(prev => prev.filter(t => t.userId !== tid)); }; const handleGroupUpdated = (updatedGroup) => { if (updatedGroup.id === group.id) onGroupUpdated?.(); }; socket.on('message:new', handleNew); socket.on('message:deleted', handleDeleted); socket.on('reaction:updated', handleReaction); socket.on('typing:start', handleTypingStart); socket.on('typing:stop', handleTypingStop); socket.on('group:updated', handleGroupUpdated); return () => { socket.off('message:new', handleNew); socket.off('message:deleted', handleDeleted); socket.off('reaction:updated', handleReaction); socket.off('typing:start', handleTypingStart); socket.off('typing:stop', handleTypingStop); socket.off('group:updated', handleGroupUpdated); }; }, [socket, group?.id, currentUser?.id]); const handleLoadMore = async () => { if (!hasMore || loading || messages.length === 0) return; const container = messagesContainerRef.current; const prevScrollHeight = container?.scrollHeight || 0; setLoading(true); try { const oldest = messages[0]; const { messages: older } = await api.getMessages(group.id, oldest.id); setMessages(prev => [...older, ...prev]); setHasMore(older.length >= 50); requestAnimationFrame(() => { if (container) container.scrollTop = container.scrollHeight - prevScrollHeight; }); } catch (e) { toast(e.message, 'error'); } finally { setLoading(false); } }; const handleSend = async ({ content, imageFile, linkPreview, emojiOnly }) => { if ((!content?.trim() && !imageFile) || !group) return; const replyToId = replyTo?.id || null; setReplyTo(null); try { if (imageFile) { await api.uploadImage(group.id, imageFile, { replyToId, content: content?.trim() || '' }); } else { await api.sendMessage(group.id, { content: content.trim(), replyToId, linkPreview, emojiOnly }); } } catch (e) { toast(e.message || 'Failed to send', 'error'); } }; const handleDelete = async (msgId) => { try { await api.deleteMessage(msgId); } catch (e) { toast(e.message || 'Could not delete', 'error'); } }; const handleReact = async (msgId, emoji) => { try { await api.toggleReaction(msgId, emoji); } catch (e) { toast(e.message || 'Could not react', 'error'); } }; const handleReply = (msg) => { setReplyTo(msg); }; const handleDirectMessage = (dmGroup) => { onDirectMessage?.(dmGroup); }; if (!group) { return (
Choose a channel or direct message to start chatting