// Realtime chat events, ported from a Golem15 SPA's chatEvents.ts (the // created event also carries root_id, so replies stay out of the main // list). Publications arrive as {event, payload, timestamp} (lighthouse). Conversation channels carry ids only: content is always // fetched over the JWT REST API. Only user:{me}, which golem15.user // authorizes for its owner alone, carries a full message (chat:message). import type { ChatConversationRow, ChatMessage, ChatReaction } from './types' export type ChatEvent = /** created.chat.message on chat:conversation:{id}: fetch the message. */ | { kind: 'created'; id: number; conversationId: number; senderId: number; rootId?: number } /** chat:message on user:{me}: a message from someone else, any conversation. */ | { kind: 'chatMessage'; conversationId: number; message: ChatMessage } /** typing.chat.message on chat:conversation:{id}. */ | { kind: 'typing'; conversationId: number; userId: number } /** chat:read on user:{me}: someone else read a conversation. */ | { kind: 'read'; conversationId: number; userId: number } /** chat:unread on user:{me}: the user's total in the context. */ | { kind: 'unread'; count: number } /** mentions.changed on user:{me} (golem15.chatchannels). */ | { kind: 'mentions' } /** reacted.chat.message on chat:conversation:{id}: one user added or removed one key. */ | { kind: 'reacted'; id: number; conversationId: number; userId: number; key: string; added: boolean } /** updated.chat.message on chat:conversation:{id}: the message was edited, refetch it. */ | { kind: 'updated'; id: number; conversationId: number } /** deleted.chat.message on chat:conversation:{id}. */ | { kind: 'deleted'; id: number; conversationId: number } function isObject(v: unknown): v is Record { return typeof v === 'object' && v !== null && !Array.isArray(v) } function id(v: unknown): number | null { return typeof v === 'number' && Number.isInteger(v) && v > 0 ? v : null } function isMessage(v: unknown): v is ChatMessage { if (!isObject(v)) return false return ( id(v.id) !== null && id(v.conversation_id) !== null && id(v.sender_id) !== null && typeof v.created_at === 'string' && (v.content === null || typeof v.content === 'string') && Array.isArray(v.attachments) ) } /** parsePublication turns channel data into a typed event; anything unexpected is null. */ export function parsePublication(data: unknown): ChatEvent | null { if (!isObject(data) || typeof data.event !== 'string') return null const p = data.payload switch (data.event) { case 'created.chat.message': { if (!isObject(p)) return null const mid = id(p.id) const conv = id(p.conversation_id) const sender = id(p.sender_id) if (mid === null || conv === null || sender === null) return null const root = id(p.root_id) return root === null ? { kind: 'created', id: mid, conversationId: conv, senderId: sender } : { kind: 'created', id: mid, conversationId: conv, senderId: sender, rootId: root } } case 'chat:message': { if (!isObject(p) || !isMessage(p.message)) return null const conv = id(p.conversation_id) if (conv === null || conv !== p.message.conversation_id) return null return { kind: 'chatMessage', conversationId: conv, message: p.message } } case 'typing.chat.message': { if (!isObject(p) || p.action !== 'typing-start') return null const conv = id(p.conversation_id) const user = id(p.user_id) if (conv === null || user === null) return null return { kind: 'typing', conversationId: conv, userId: user } } case 'chat:read': { if (!isObject(p)) return null const conv = id(p.conversation_id) const user = id(p.user_id) if (conv === null || user === null) return null return { kind: 'read', conversationId: conv, userId: user } } case 'chat:unread': { if (!isObject(p) || typeof p.count !== 'number' || !Number.isInteger(p.count) || p.count < 0) return null return { kind: 'unread', count: p.count } } case 'mentions.changed': return { kind: 'mentions' } case 'reacted.chat.message': { if (!isObject(p)) return null const mid = id(p.id) const conv = id(p.conversation_id) const user = id(p.user_id) if (mid === null || conv === null || user === null) return null if (typeof p.key !== 'string' || p.key === '' || (p.action !== 'added' && p.action !== 'removed')) return null return { kind: 'reacted', id: mid, conversationId: conv, userId: user, key: p.key, added: p.action === 'added' } } case 'updated.chat.message': case 'deleted.chat.message': { if (!isObject(p)) return null const mid = id(p.id) const conv = id(p.conversation_id) if (mid === null || conv === null) return null return { kind: data.event === 'updated.chat.message' ? 'updated' : 'deleted', id: mid, conversationId: conv } } default: return null } } /** * needsFetch reports whether a created event names a message of a loaded * conversation that is not in it yet. Unloaded conversations load their * latest page when opened. */ export function needsFetch(ev: ChatEvent, messages: Record): boolean { if (ev.kind !== 'created') return false const list = messages[ev.conversationId] return !!list && !list.some((m) => m.id === ev.id) } export interface ApplyOptions { /** The user is looking at this conversation: no unread increment. */ seen: boolean } /** * applyChatMessage updates the DM rows for a message from someone else: * preview, order (through last_message) and unread. A DM the user did not * have yet gets a new row. Returns a new array; rows are copied when changed. */ export function applyChatMessage(rows: ChatConversationRow[], m: ChatMessage, { seen }: ApplyOptions): ChatConversationRow[] { const last = { id: m.id, sender_id: m.sender_id, content: m.content ?? '', created_at: m.created_at } const i = rows.findIndex((r) => r.id === m.conversation_id) if (i === -1) { return [{ id: m.conversation_id, type: 'dm', other_user_id: m.sender_id, unread: seen ? 0 : 1, last_message: last }, ...rows] } const row = rows[i] if (row.last_message && row.last_message.id === m.id) return rows const newer = !row.last_message || Date.parse(m.created_at) >= Date.parse(row.last_message.created_at) const next = { ...row, unread: seen ? row.unread : row.unread + 1, last_message: newer ? last : row.last_message } return rows.map((r, j) => (j === i ? next : r)) } /** * applyReaction sets one user's reaction on one key, idempotently: adding a * user already listed or removing one who is not changes nothing (so the * echo of your own optimistic toggle never counts twice). A chip that drops * to zero disappears; a new key is placed in the allowed order when known. * Returns the same array when nothing changed. */ export function applyReaction( reactions: readonly ChatReaction[] | undefined, key: string, userId: number, add: boolean, order: readonly string[] = [], ): ChatReaction[] { const list = reactions ? [...reactions] : [] const i = list.findIndex((r) => r.key === key) const has = i >= 0 && list[i].user_ids.includes(userId) if (add === has) return reactions ? (reactions as ChatReaction[]) : list if (add) { if (i >= 0) { list[i] = { ...list[i], count: list[i].count + 1, user_ids: [...list[i].user_ids, userId] } return list } const chip = { key, count: 1, user_ids: [userId] } const rank = (k: string) => { const r = order.indexOf(k) return r < 0 ? order.length : r } let at = list.length if (order.includes(key)) { at = list.findIndex((r) => rank(r.key) > rank(key)) if (at < 0) at = list.length } list.splice(at, 0, chip) return list } const user_ids = list[i].user_ids.filter((u) => u !== userId) if (user_ids.length === 0) list.splice(i, 1) else list[i] = { ...list[i], count: Math.max(0, list[i].count - 1), user_ids } return list }