// The chat store: membership, channels, the open conversation, messages and // drafts, as useState keys prefixed chat: (no Pinia). Every component that // calls useChat() shares the same state. import type { ChatChannel, ChatMessage } from '../lib/types' /** The fallback page size of the message list. */ export const MESSAGE_PAGE = 50 export function useChat() { const api = useChatApi() const config = useChatConfig() /** undefined: not known yet; false: outside the community. */ const member = useState('chat:member', () => undefined) const channels = useState('chat:channels', () => []) /** The open conversation id. */ const activeId = useState('chat:activeId', () => null) const messages = useState>('chat:messages', () => ({})) const drafts = useState>('chat:drafts', () => ({})) const error = useState('chat:error', () => '') const sending = useState('chat:sending', () => false) /** Loads the bootstrap; without public.chat.hostApiBase it logs an error and stops. */ async function start(): Promise { if (!config.hostApiBase) { console.error('vue-chat-layer: runtimeConfig.public.chat.hostApiBase is not set; the chat does not start') return } try { const b = await api.bootstrap() if (!b.member) { member.value = false channels.value = [] return } member.value = true channels.value = b.channels.map((c) => ({ ...c })) } catch { error.value = 'bootstrap' } } /** Opens a channel: the conversation route joins it, then the latest page loads. */ async function open(channel: ChatChannel): Promise { error.value = '' await api.openConversation('channel', channel.id) activeId.value = channel.conversation_id messages.value[channel.conversation_id] = await api.messages(channel.conversation_id, { limit: MESSAGE_PAGE }) } /** Sends text to the open conversation; the message appears once the API answers. */ async function send(text: string): Promise { const id = activeId.value const content = text.trim() if (id === null || !content || sending.value) return false sending.value = true try { const m = await api.send(id, { content }) const list = messages.value[id] ?? (messages.value[id] = []) if (!list.some((x) => x.id === m.id)) list.push(m) drafts.value[id] = '' return true } catch { error.value = 'send' return false } finally { sending.value = false } } return { member, channels, activeId, messages, drafts, error, sending, start, open, send } }