import { q } from "@thorium/context/AppContext"; import { useStation } from "@thorium/routes/station/useStation"; import Button from "@thorium/ui/Button"; import { InputField } from "@thorium/ui/Core"; import { Icon } from "@thorium/ui/Icon"; import Input from "@thorium/ui/Input"; import Select from "@thorium/ui/Select"; import { cn } from "@thorium/utils/cn"; import { useMemo, useState } from "react"; type Conversation = { sender: string; recipient: string; lastTimestamp: number; messages: { content: string; sender: string; timestamp: number }[]; }; export function MessagingCore() { const { shipId } = useStation(); const [messageGroups] = q.messaging.messageGroups.useNetRequest({ shipId }); const [ship] = q.ship.get.useNetRequest({ shipId }); const [selectedConversationDestination, setSelectedConversationDestination] = useState< string | null >(null); const [sender, setSender] = useState(""); const [alertSender, setAlertSender] = useState(false); const stations = ship?.stations.map((s) => s.name) || []; const conversations = useConversations(); const selectedConversation = conversations.find( (c) => c.recipient === selectedConversationDestination, ); return (
(typeof value === "string" ? setSender(value) : null)} > {sender || <> }
); } export function useConversations(station?: string) { const { shipId } = useStation(); const [messages] = q.messaging.messages.useNetRequest({ shipId, station }); const [ship] = q.ship.get.useNetRequest({ shipId }); const stations = ship?.stations.map((s) => s.name) || []; const conversations = useMemo(() => { const conversations = new Map(); for (const message of messages) { const key = stations.includes(message.sender) && stations.includes(message.destination) ? [message.sender, message.destination].sort().join("") : stations.includes(message.destination) ? message.destination : message.sender; const conversation = conversations.get(key) || { sender: stations.includes(message.sender) ? message.destination : message.sender, recipient: stations.includes(message.sender) ? message.sender : message.destination, messages: [], lastTimestamp: 0, }; conversation.messages.push({ content: message.content, sender: message.sender, timestamp: message.timestamp, }); conversation.lastTimestamp = Math.max(conversation.lastTimestamp, message.timestamp); conversation.sender = stations.includes(message.sender) ? message.destination : message.sender; conversations.set(key, conversation); } const sortedConversations: Conversation[] = []; for (const conversation of conversations.values()) { sortedConversations.push(conversation); } sortedConversations.sort((a, b) => a.lastTimestamp - b.lastTimestamp); return sortedConversations; }, [messages, stations]); return conversations; }