/**
* Pure chat actions: (data, …args) → new data. The store (store.ts) only wires them to React; tests and undo use
* them directly. Nothing here reads the clock or the DOM: callers pass `now` and new ids in.
*/
import { firstName } from "@/lib/contacts"
import type { Attachment, Contact, Conversation, Message, MessageStatus, MuteDuration, Presence, Profile } from "./types"
export interface ChatData {
me: Profile
contacts: Record<string, Contact>
conversations: Conversation[]
/** Messages per conversation, oldest first. */
messages: Record<string, Message[]>
drafts: Record<string, string>
}
type Patch<T> = Partial<T> | ((value: T) => Partial<T>)
function updateConversation(data: ChatData, id: string, patch: Patch<Conversation>): ChatData {
return {
...data,
conversations: data.conversations.map((c) =>
c.id === id ? { ...c, ...(typeof patch === "function" ? patch(c) : patch) } : c
),
}
}
function updateMessage(data: ChatData, conversationId: string, messageId: string, patch: Patch<Message>): ChatData {
const list = data.messages[conversationId]
if (!list) return data
return {
...data,
messages: {
...data.messages,
[conversationId]: list.map((m) =>
m.id === messageId ? { ...m, ...(typeof patch === "function" ? patch(m) : patch) } : m
),
},
}
}
function append(data: ChatData, conversationId: string, message: Message): ChatData {
return {
...data,
messages: { ...data.messages, [conversationId]: [...(data.messages[conversationId] ?? []), message] },
}
}
export function nameOf(data: ChatData, id: string) {
if (id === "me") return "You"
return data.contacts[id]?.name ?? "Someone"
}
function systemMessage(conversationId: string, id: string, text: string, now: number): Message {
return { id, conversationId, senderId: "system", kind: "system", text, createdAt: now }
}
export interface OutgoingMessage {
id: string
text: string
attachments?: Attachment[]
replyToId?: string
now: number
}
export function sendMessage(data: ChatData, conversationId: string, m: OutgoingMessage): ChatData {
const message: Message = {
id: m.id,
conversationId,
senderId: "me",
kind: "text",
text: m.text,
attachments: m.attachments?.length ? m.attachments : undefined,
replyToId: m.replyToId,
createdAt: m.now,
status: "sending",
}
const next = append(data, conversationId, message)
return updateConversation({ ...next, drafts: { ...next.drafts, [conversationId]: "" } }, conversationId, {
archived: false,
unread: 0,
markedUnread: false,
})
}
export function addNote(data: ChatData, conversationId: string, m: OutgoingMessage): ChatData {
const note: Message = {
id: m.id,
conversationId,
senderId: "me",
kind: "note",
text: m.text,
attachments: m.attachments?.length ? m.attachments : undefined,
replyToId: m.replyToId,
createdAt: m.now,
}
const next = append(data, conversationId, note)
return { ...next, drafts: { ...next.drafts, [conversationId]: "" } }
}
/** An incoming message. `active` = the conversation is open and scrolled to the newest message. */
export function receiveMessage(data: ChatData, message: Message, active: boolean): ChatData {
const next = append(data, message.conversationId, message)
return updateConversation(next, message.conversationId, (c) => ({
archived: c.mutedUntil ? c.archived : false,
unread: active ? 0 : c.unread + 1,
}))
}
export function setMessageStatus(data: ChatData, conversationId: string, messageId: string, status: MessageStatus) {
return updateMessage(data, conversationId, messageId, { status })
}
/** Marks every message of mine in the conversation as read (the other side opened it). */
export function markMineRead(data: ChatData, conversationId: string): ChatData {
const list = data.messages[conversationId]
if (!list) return data
return {
...data,
messages: {
...data.messages,
[conversationId]: list.map((m) => (m.senderId === "me" && m.kind === "text" && m.status !== "read" ? { ...m, status: "read" } : m)),
},
}
}
/** Toggles `userId`'s reaction. */
export function react(data: ChatData, conversationId: string, messageId: string, emoji: string, userId = "me"): ChatData {
return updateMessage(data, conversationId, messageId, (m) => {
const reactions = (m.reactions ?? []).map((r) => ({ ...r, userIds: [...r.userIds] }))
const existing = reactions.find((r) => r.emoji === emoji)
if (existing) {
existing.userIds = existing.userIds.includes(userId)
? existing.userIds.filter((u) => u !== userId)
: [...existing.userIds, userId]
} else {
reactions.push({ emoji, userIds: [userId] })
}
return { reactions: reactions.filter((r) => r.userIds.length > 0) }
})
}
export function editMessage(data: ChatData, conversationId: string, messageId: string, text: string, now: number) {
return updateMessage(data, conversationId, messageId, (m) => (m.text === text ? {} : { text, editedAt: now }))
}
export function deleteMessage(data: ChatData, conversationId: string, messageId: string) {
return updateMessage(data, conversationId, messageId, {
deleted: true,
text: "",
attachments: undefined,
link: undefined,
reactions: undefined,
pinned: false,
})
}
export function pinMessage(data: ChatData, conversationId: string, messageId: string, pinned?: boolean) {
return updateMessage(data, conversationId, messageId, (m) => ({ pinned: pinned ?? !m.pinned }))
}
export function forwardMessage(
data: ChatData,
source: Message,
targets: Array<{ conversationId: string; id: string }>,
now: number
): ChatData {
let next = data
const from = source.senderId === "me" ? data.me.name : nameOf(data, source.senderId)
for (const target of targets) {
next = append(next, target.conversationId, {
id: target.id,
conversationId: target.conversationId,
senderId: "me",
kind: "text",
text: source.text,
attachments: source.attachments?.map((a) => ({ ...a, progress: undefined })),
link: source.link,
forwardedFrom: from,
createdAt: now,
status: "sent",
})
next = updateConversation(next, target.conversationId, { archived: false })
}
return next
}
export function pinChat(data: ChatData, conversationId: string, pinned?: boolean) {
return updateConversation(data, conversationId, (c) => ({ pinned: pinned ?? !c.pinned }))
}
const MUTE_MS: Record<Exclude<MuteDuration, "always">, number> = {
"1h": 3600_000,
"8h": 8 * 3600_000,
"1w": 7 * 24 * 3600_000,
}
/** Mutes for a duration, or unmutes with `null`. */
export function muteChat(data: ChatData, conversationId: string, duration: MuteDuration | null, now: number) {
const mutedUntil = duration === null ? 0 : duration === "always" ? Infinity : now + MUTE_MS[duration]
return updateConversation(data, conversationId, { mutedUntil })
}
export function toggleFavourite(data: ChatData, conversationId: string, favourite?: boolean) {
return updateConversation(data, conversationId, (c) => ({ favourite: favourite ?? !c.favourite }))
}
export function markRead(data: ChatData, conversationId: string) {
return updateConversation(data, conversationId, { unread: 0, markedUnread: false })
}
export function markUnread(data: ChatData, conversationId: string) {
return updateConversation(data, conversationId, (c) => ({ markedUnread: c.unread === 0 }))
}
export function archiveChat(data: ChatData, conversationId: string, archived?: boolean) {
return updateConversation(data, conversationId, (c) => {
const value = archived ?? !c.archived
return { archived: value, pinned: value ? false : c.pinned }
})
}
export function clearChat(data: ChatData, conversationId: string, systemId: string, now: number): ChatData {
const next = updateConversation(data, conversationId, { unread: 0, markedUnread: false })
return {
...next,
messages: { ...next.messages, [conversationId]: [systemMessage(conversationId, systemId, "Chat cleared", now)] },
}
}
export function blockContact(data: ChatData, contactId: string, blocked: boolean, systemId: string, now: number) {
const dm = data.conversations.find((c) => c.kind === "dm" && c.contactId === contactId)
if (!dm) return data
const name = nameOf(data, contactId)
const next = updateConversation(data, dm.id, { blocked })
return append(next, dm.id, systemMessage(dm.id, systemId, blocked ? `You blocked ${name}` : `You unblocked ${name}`, now))
}
/** Removes the contact's direct conversation and the contact itself. */
export function deleteContact(data: ChatData, contactId: string): ChatData {
const dm = data.conversations.find((c) => c.kind === "dm" && c.contactId === contactId)
const contacts = { ...data.contacts }
delete contacts[contactId]
const messages = { ...data.messages }
if (dm) delete messages[dm.id]
return {
...data,
contacts,
messages,
conversations: data.conversations
.filter((c) => c.id !== dm?.id)
.map((c) => (c.memberIds.includes(contactId) ? { ...c, memberIds: c.memberIds.filter((m) => m !== contactId) } : c)),
}
}
export function leaveGroup(data: ChatData, conversationId: string): ChatData {
const messages = { ...data.messages }
delete messages[conversationId]
return { ...data, messages, conversations: data.conversations.filter((c) => c.id !== conversationId) }
}
export function addMembers(data: ChatData, conversationId: string, contactIds: string[], systemId: string, now: number) {
const conversation = data.conversations.find((c) => c.id === conversationId)
if (!conversation) return data
const fresh = contactIds.filter((id) => !conversation.memberIds.includes(id))
if (!fresh.length) return data
const next = updateConversation(data, conversationId, { memberIds: [...conversation.memberIds, ...fresh] })
const names = fresh.map((id) => firstName(nameOf(data, id)))
const list = names.length > 1 ? `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}` : names[0]
return append(next, conversationId, systemMessage(conversationId, systemId, `You added ${list}`, now))
}
export interface NewGroup {
id: string
name: string
description?: string
photo?: string
memberIds: string[]
quickReplies: string[]
now: number
systemIds: [string, string]
}
export function createGroup(data: ChatData, g: NewGroup): ChatData {
const conversation: Conversation = {
id: g.id,
kind: "group",
name: g.name,
description: g.description,
photo: g.photo,
memberIds: ["me"],
adminIds: ["me"],
pinned: false,
favourite: false,
mutedUntil: 0,
archived: false,
unread: 0,
markedUnread: false,
quickReplies: g.quickReplies,
createdAt: g.now,
}
const next: ChatData = { ...data, conversations: [conversation, ...data.conversations] }
const created = append(next, g.id, systemMessage(g.id, g.systemIds[0], `You created the group “${g.name}”`, g.now))
return addMembers(created, g.id, g.memberIds, g.systemIds[1], g.now)
}
/** Opens (or creates) the direct conversation with a contact; returns the data and its id. */
export function ensureDirect(data: ChatData, contactId: string, now: number, quickReplies: string[]): [ChatData, string] {
const existing = data.conversations.find((c) => c.kind === "dm" && c.contactId === contactId)
if (existing) return [existing.archived ? updateConversation(data, existing.id, { archived: false }) : data, existing.id]
const conversation: Conversation = {
id: contactId,
kind: "dm",
contactId,
memberIds: ["me", contactId],
adminIds: [],
pinned: false,
favourite: false,
mutedUntil: 0,
archived: false,
unread: 0,
markedUnread: false,
quickReplies,
createdAt: now,
}
return [{ ...data, conversations: [conversation, ...data.conversations], messages: { ...data.messages, [contactId]: [] } }, contactId]
}
export function updateProfile(data: ChatData, patch: Partial<Profile>): ChatData {
return { ...data, me: { ...data.me, ...patch } }
}
export function setStatus(data: ChatData, presence: Presence): ChatData {
return { ...data, me: { ...data.me, presence } }
}
export function setDraft(data: ChatData, conversationId: string, text: string): ChatData {
if ((data.drafts[conversationId] ?? "") === text) return data
return { ...data, drafts: { ...data.drafts, [conversationId]: text } }
}
export function updateAttachment(data: ChatData, conversationId: string, messageId: string, attachmentId: string, patch: Partial<Attachment>) {
return updateMessage(data, conversationId, messageId, (m) => ({
attachments: m.attachments?.map((a) => (a.id === attachmentId ? { ...a, ...patch } : a)),
}))
}
export function addSystem(data: ChatData, conversationId: string, id: string, text: string, now: number) {
return append(data, conversationId, systemMessage(conversationId, id, text, now))
}