import { useEffect, useRef, useState } from 'react' import { useWaste } from '../store' export function MessagePane() { const { messages, activeRoom, activeNetworkId, localPeer, connectedPeers, send } = useWaste() const [draft, setDraft] = useState('') const bottomRef = useRef(null) const roomMessages = messages[activeRoom] ?? [] useEffect(() => { bottomRef.current?.scrollIntoView({ behavior: 'smooth' }) }, [roomMessages.length]) function submit(e: React.FormEvent) { e.preventDefault() const text = draft.trim() if (!text || !activeNetworkId) return if (activeRoom.startsWith('dm:')) { const toPeerID = activeRoom.slice(3) const peer = connectedPeers.find(p => p.id.startsWith(toPeerID) || p.id === toPeerID) if (peer) { send({ type: 'send_message', network_id: activeNetworkId, room: activeRoom, body: text, to: peer.id }) } } else { send({ type: 'send_message', network_id: activeNetworkId, room: activeRoom, body: text }) } setDraft('') } function aliasFor(fromId: string) { if (fromId === localPeer?.id) return localPeer.alias return connectedPeers.find(p => p.id === fromId)?.alias ?? fromId.slice(0, 8) } const roomLabel = activeRoom.startsWith('dm:') ? `@ ${activeRoom.slice(3, 11)}…` : `# ${activeRoom}` return (
{roomLabel}
{roomMessages.map((msg, i) => { const mine = msg.from === localPeer?.id const alias = aliasFor(msg.from) const time = new Date(msg.ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false }) return (
{time} {alias} {msg.text}
) })}
setDraft(e.target.value)} placeholder={`Message ${roomLabel}`} autoComplete="off" />
) }