- realtime.ts: the page's one Centrifuge client, setRealtimeAuth, onUserEvent for user:{me} events the chat does not handle
- chatEvents, chatFormat, chatText, chatUnread, format, media, tabs ported; copy passed in localized
- useChat over useState: channels with join and leave, DMs, member list, unread and mention counts, read marks, typing, presence, polling fallback
- ChatPanel, ChatHeader, ChatMessage, ChatDmList, ChatMemberPicker, ChatMentionPopup, ChatAvatar, ChatIcon, ChatNotices
- EN and PL strings
1119 lines
40 KiB
TypeScript
1119 lines
40 KiB
TypeScript
// The chat store, ported from a Golem15 SPA's Pinia setup store as a
|
|
// composable over useState keys prefixed chat: (no Pinia). The SPA's one
|
|
// group conversation became the host's list of channels: `channels`,
|
|
// `activeId` (the open conversation) and `kind` ('channel' or 'dm').
|
|
//
|
|
// One store per Nuxt app; every component that calls useChat() shares it.
|
|
// It runs in the browser only (start() does nothing on the server).
|
|
//
|
|
// Realtime: user:{me} for the whole member session (messages from others in
|
|
// any conversation, read marks, mention changes; every other event goes to
|
|
// onUserEvent handlers), and the open conversation's channel while it is
|
|
// open (created, typing, edits, deletions, presence). Without realtime the
|
|
// open conversation is polled every 15 s and the counts every 60 s.
|
|
import { computed, reactive, ref, shallowRef } from 'vue'
|
|
import { ChatApiError, userIdFromToken } from '../lib/client'
|
|
import { applyChatMessage, needsFetch, parsePublication, type ChatEvent } from '../lib/chatEvents'
|
|
import { setFormatLocale } from '../lib/format'
|
|
import {
|
|
disconnect as disconnectRealtime,
|
|
dispatchUserEvent,
|
|
hasRealtimeAuth,
|
|
onConnection,
|
|
onUnavailable,
|
|
presence as fetchPresence,
|
|
setRealtimeAuth,
|
|
subscribe,
|
|
type ChannelHandle,
|
|
type ConnectionState,
|
|
type PresenceClient,
|
|
} from '../lib/realtime'
|
|
import type { ChatChannel, ChatConversationRow, ChatLimits, ChatMember, ChatMessage, ChatSendBody } from '../lib/types'
|
|
|
|
export interface ChatDraft {
|
|
text: string
|
|
/** The send error line (an i18n key under chat.), cleared on the next input or send. */
|
|
error: string
|
|
/** A server message shown with the error (a 422 field error), or ''. */
|
|
detail: string
|
|
sending: boolean
|
|
}
|
|
|
|
/** Where a list was scrolled: restored when the list mounts again. */
|
|
export interface ChatAnchor {
|
|
atBottom: boolean
|
|
/** The first visible message. */
|
|
messageId: number | null
|
|
/** Its top relative to the list's scrollTop. */
|
|
offset: number
|
|
}
|
|
|
|
/** The open conversation's kind. */
|
|
export type ChatKind = 'channel' | 'dm'
|
|
|
|
/**
|
|
* The chat's realtime link: connecting (first connect), connected,
|
|
* reconnecting (SDK backoff), unavailable (token refused for good, or no
|
|
* realtime at all: the chat polls). idle before a member session starts it.
|
|
*/
|
|
export type ChatConnection = 'idle' | 'connecting' | 'connected' | 'reconnecting' | 'unavailable'
|
|
|
|
/** Without realtime the open conversation is polled every 15 s and the counts every 60 s. */
|
|
export const POLL_ACTIVE_MS = 15_000
|
|
export const POLL_COUNTS_MS = 60_000
|
|
/** One read POST per conversation within this window. */
|
|
export const READ_DEBOUNCE_MS = 500
|
|
export const MESSAGE_PAGE = 50
|
|
/** The composer emits typing at most once every 3 s per conversation. */
|
|
export const TYPING_THROTTLE_MS = 3_000
|
|
/** A typing entry expires 6 s after that person's last typing event. */
|
|
export const TYPING_EXPIRY_MS = 6_000
|
|
|
|
const EMPTY_DRAFT: Readonly<ChatDraft> = Object.freeze({ text: '', error: '', detail: '', sending: false })
|
|
|
|
/** The send-error key (chat.error.*) for a failed POST. */
|
|
export function sendErrorKey(e: unknown): string {
|
|
const status = e instanceof ChatApiError ? e.status : -1
|
|
if (status === 0) return 'error.offline'
|
|
if (status === 429) return 'error.tooFast'
|
|
if (status === 403 || status === 404) return 'error.noAccess'
|
|
if (status === 400 || status === 422) return 'error.refused'
|
|
return 'error.send'
|
|
}
|
|
|
|
/** The DM-start error key (the chat-dm bucket allows 10 a minute). */
|
|
export function dmErrorKey(e: unknown): string {
|
|
if (e instanceof ChatApiError && e.status === 429) return 'error.tooManyDms'
|
|
if (e instanceof ChatApiError && e.status === 0) return 'error.offline'
|
|
return 'error.dm'
|
|
}
|
|
|
|
/** The message as shown once deleted: no text, reactions, attachments or metadata. */
|
|
export function markDeleted(m: ChatMessage) {
|
|
m.deleted_at = m.deleted_at ?? new Date().toISOString()
|
|
m.content = null
|
|
m.reactions = []
|
|
m.attachments = []
|
|
m.metadata = undefined
|
|
}
|
|
|
|
/**
|
|
* Marks deleted the loaded messages a fresh latest page leaves out although
|
|
* it covers them: up to lastBefore (the newest id loaded when the page was
|
|
* requested) and from the page's first id, or from the start when the page
|
|
* is short. The list API leaves deleted messages out, so a missing one was
|
|
* deleted.
|
|
*/
|
|
export function markMissingDeleted(old: ChatMessage[], page: readonly ChatMessage[], lastBefore: number) {
|
|
const present = new Set(page.map((m) => m.id))
|
|
const from = page.length < MESSAGE_PAGE ? 0 : (page[0]?.id ?? Infinity)
|
|
for (const m of old) {
|
|
if (m.deleted_at || present.has(m.id) || m.id < from || m.id > lastBefore) continue
|
|
markDeleted(m)
|
|
}
|
|
}
|
|
|
|
const conversationChannel = (id: number) => `chat:conversation:${id}`
|
|
|
|
/** The window has focus; true outside a browser. */
|
|
function pageFocused(): boolean {
|
|
return typeof document === 'undefined' || typeof document.hasFocus !== 'function' || document.hasFocus()
|
|
}
|
|
|
|
/** Inserts a message in id order unless it is already there. */
|
|
function insertMessage(list: ChatMessage[], m: ChatMessage): boolean {
|
|
if (list.some((x) => x.id === m.id)) return false
|
|
let i = list.length
|
|
while (i > 0 && list[i - 1].id > m.id) i--
|
|
list.splice(i, 0, m)
|
|
return true
|
|
}
|
|
|
|
function createChatStore() {
|
|
const api = useChatApi()
|
|
const auth = useChatAuth()
|
|
const config = useChatConfig()
|
|
const notice = useChatNotice()
|
|
|
|
const userId = useState<number | null>('chat:userId', () => null)
|
|
/** undefined: not known yet (bootstrap in flight). */
|
|
const member = useState<boolean | undefined>('chat:member', () => undefined)
|
|
const moderator = useState('chat:moderator', () => false)
|
|
const context = useState<{ type: string; id: number } | null>('chat:context', () => null)
|
|
const channels = useState<ChatChannel[]>('chat:channels', () => [])
|
|
const conversations = useState<ChatConversationRow[]>('chat:conversations', () => [])
|
|
const limits = useState<ChatLimits | null>('chat:limits', () => null)
|
|
/** The open conversation id. */
|
|
const activeId = useState<number | null>('chat:activeId', () => null)
|
|
const kind = useState<ChatKind | null>('chat:kind', () => null)
|
|
const dmError = useState('chat:dmError', () => '')
|
|
/** Messages per conversation id, oldest first; absent until loaded. */
|
|
const messages = useState<Record<number, ChatMessage[]>>('chat:messages', () => ({}))
|
|
const loading = useState<Record<number, boolean>>('chat:loading', () => ({}))
|
|
const errors = useState<Record<number, string>>('chat:errors', () => ({}))
|
|
const drafts = useState<Record<number, ChatDraft>>('chat:drafts', () => ({}))
|
|
const anchors = useState<Record<number, ChatAnchor>>('chat:anchors', () => ({}))
|
|
/** Members by id (the others; the caller is not listed). */
|
|
const memberRows = useState<Record<number, ChatMember>>('chat:members', () => ({}))
|
|
const membersState = useState<'idle' | 'loading' | 'ready' | 'error'>('chat:membersState', () => 'idle')
|
|
const bootstrapState = useState<'idle' | 'loading' | 'ready' | 'error'>('chat:bootstrapState', () => 'idle')
|
|
const connection = useState<ChatConnection>('chat:connection', () => 'idle')
|
|
/** A chat view is on screen (set by ChatPanel and the floating panel). */
|
|
const panelVisible = useState('chat:panelVisible', () => false)
|
|
const reachedStart = useState<Record<number, boolean>>('chat:reachedStart', () => ({}))
|
|
const olderLoading = useState<Record<number, boolean>>('chat:olderLoading', () => ({}))
|
|
const olderError = useState<Record<number, string>>('chat:olderError', () => ({}))
|
|
/** Who is typing, per conversation (others only). */
|
|
const typing = useState<Record<number, number[]>>('chat:typing', () => ({}))
|
|
/** Presence of the open channel: Centrifugo client id to user id. */
|
|
const presenceClients = shallowRef<Map<string, number>>(new Map())
|
|
const presenceAvailable = ref(false)
|
|
|
|
/** Bumped by reset(): answers of an older session are dropped. */
|
|
let generation = 0
|
|
let bootstrapping: Promise<void> | null = null
|
|
let membersLoading: Promise<void> | null = null
|
|
/** Channels whose conversation route ran this session (it makes the caller a participant). */
|
|
const joinedConversations = new Set<number>()
|
|
|
|
// Realtime: user:{me} for the whole session, the open conversation while open.
|
|
let realtimeStarted = false
|
|
let userHandle: ChannelHandle | null = null
|
|
let openHandle: ChannelHandle | null = null
|
|
let openChannelId: number | null = null
|
|
let openSeq = 0
|
|
let unlisten: Array<() => void> = []
|
|
let activePoll: ReturnType<typeof setInterval> | null = null
|
|
let countsPoll: ReturnType<typeof setInterval> | null = null
|
|
const fetchingIds = new Set<number>()
|
|
const refreshing = new Map<number, Promise<void>>()
|
|
// Read marking: the newest message id already marked, the debounce timers, POSTs in flight.
|
|
const readUpTo = new Map<number, number>()
|
|
const readTimers = new Map<number, ReturnType<typeof setTimeout>>()
|
|
const readInFlight = new Set<number>()
|
|
let onVisibility: (() => void) | null = null
|
|
const typingTimers = new Map<string, ReturnType<typeof setTimeout>>()
|
|
const typingSentAt = new Map<number, number>()
|
|
|
|
const members = computed(() => new Map(Object.values(memberRows.value).map((m) => [m.id, m])))
|
|
/** Members by handle, for mentions in message bodies. */
|
|
const membersByHandle = computed(() => {
|
|
const out = new Map<string, ChatMember>()
|
|
for (const m of members.value.values()) if (m.handle) out.set(m.handle, m)
|
|
return out
|
|
})
|
|
/** The user's own handle when the host lists the caller among the members. */
|
|
const myHandle = computed(() => (userId.value !== null ? (members.value.get(userId.value)?.handle ?? null) : null))
|
|
|
|
const joinedChannels = computed(() => channels.value.filter((c) => c.joined))
|
|
const activeChannel = computed(() => (kind.value === 'channel' ? (channels.value.find((c) => c.conversation_id === activeId.value) ?? null) : null))
|
|
const activeDm = computed(() => (kind.value === 'dm' ? (conversations.value.find((c) => c.id === activeId.value) ?? null) : null))
|
|
|
|
function channelOf(conversationId: number): ChatChannel | undefined {
|
|
return channels.value.find((c) => c.conversation_id === conversationId)
|
|
}
|
|
|
|
function isChannel(conversationId: number): boolean {
|
|
return !!channelOf(conversationId)
|
|
}
|
|
|
|
/** Unread messages in one conversation. */
|
|
function unreadOf(conversationId: number): number {
|
|
const ch = channelOf(conversationId)
|
|
if (ch) return ch.unread
|
|
return conversations.value.find((c) => c.id === conversationId)?.unread ?? 0
|
|
}
|
|
|
|
/** Unread mentions of the user (channels only: DMs have none). */
|
|
function mentionsOf(conversationId: number): number {
|
|
return channelOf(conversationId)?.mentions ?? 0
|
|
}
|
|
|
|
/** The sum over DMs. */
|
|
const dmUnread = computed(() => conversations.value.reduce((n, c) => n + (c.unread > 0 ? c.unread : 0), 0))
|
|
/** Unread messages in joined channels. */
|
|
const channelUnread = computed(() => joinedChannels.value.reduce((n, c) => n + (c.unread > 0 ? c.unread : 0), 0))
|
|
const totalMentions = computed(() => (member.value ? channels.value.reduce((n, c) => n + (c.mentions > 0 ? c.mentions : 0), 0) : 0))
|
|
/** DMs plus channel mentions: the floating panel's badge. */
|
|
const attention = computed(() => (member.value ? dmUnread.value + totalMentions.value : 0))
|
|
|
|
/** Other members online in the open channel, by id. */
|
|
const othersOnline = computed(() => [...new Set(presenceClients.value.values())].filter((id) => id !== userId.value).sort((a, b) => a - b))
|
|
/** Everyone online in the open channel, you included. */
|
|
const onlineCount = computed(() => othersOnline.value.length + 1)
|
|
|
|
/** A member's online dot, while the open channel's presence is known. */
|
|
function isOnline(id: number): boolean {
|
|
return presenceAvailable.value && othersOnline.value.includes(id)
|
|
}
|
|
|
|
/** The people typing in a conversation; none without realtime. */
|
|
function typingIn(conversationId: number): number[] {
|
|
if (connection.value === 'unavailable') return []
|
|
return typing.value[conversationId] ?? []
|
|
}
|
|
|
|
/** The user's DMs, last message newest first; DMs without messages last. */
|
|
const dmRows = computed(() =>
|
|
[...conversations.value].sort((a, b) => {
|
|
const ta = a.last_message ? Date.parse(a.last_message.created_at) : -Infinity
|
|
const tb = b.last_message ? Date.parse(b.last_message.created_at) : -Infinity
|
|
return tb - ta || b.id - a.id
|
|
}),
|
|
)
|
|
|
|
function applyBootstrap(b: Awaited<ReturnType<typeof api.bootstrap>>) {
|
|
if (!b.member) {
|
|
stopRealtime()
|
|
member.value = false
|
|
moderator.value = false
|
|
context.value = null
|
|
channels.value = []
|
|
conversations.value = []
|
|
limits.value = null
|
|
activeId.value = null
|
|
kind.value = null
|
|
messages.value = {}
|
|
return
|
|
}
|
|
member.value = true
|
|
moderator.value = !!b.moderator
|
|
context.value = b.context
|
|
channels.value = (b.channels ?? []).map((c) => ({ ...c }))
|
|
conversations.value = (b.conversations ?? []).map((c) => ({ ...c }))
|
|
limits.value = b.limits
|
|
// A read still on its way must not bring the old count back.
|
|
for (const id of [...readTimers.keys(), ...readInFlight]) zeroLocal(id)
|
|
if (activeId.value !== null && !isChannel(activeId.value) && !conversations.value.some((c) => c.id === activeId.value)) {
|
|
activeId.value = null
|
|
kind.value = null
|
|
}
|
|
}
|
|
|
|
/** Re-checks membership and refreshes channels, DMs and counts. */
|
|
function bootstrap(): Promise<void> {
|
|
if (bootstrapping) return bootstrapping
|
|
const gen = generation
|
|
// A refetch (counts, gap fill, polling) keeps the last values on failure, silently.
|
|
const refetch = bootstrapState.value === 'ready'
|
|
if (!refetch) bootstrapState.value = 'loading'
|
|
bootstrapping = (async () => {
|
|
try {
|
|
const b = await api.bootstrap()
|
|
if (gen !== generation) return
|
|
applyBootstrap(b)
|
|
bootstrapState.value = 'ready'
|
|
} catch {
|
|
if (gen === generation && !refetch) bootstrapState.value = 'error'
|
|
} finally {
|
|
if (gen === generation) bootstrapping = null
|
|
}
|
|
})()
|
|
return bootstrapping
|
|
}
|
|
|
|
function currentUserId(): number | null {
|
|
try {
|
|
const own = auth.userId?.()
|
|
if (typeof own === 'number' && own > 0) return own
|
|
} catch {
|
|
/* fall back to the token */
|
|
}
|
|
return userIdFromToken(auth.token())
|
|
}
|
|
|
|
/**
|
|
* Starts the chat for the signed-in user: the bootstrap, the member list
|
|
* and realtime. Membership is revalidated on every call; a different user
|
|
* resets the store first. Without public.chat.hostApiBase it logs an error
|
|
* and does nothing.
|
|
*/
|
|
async function start(locale?: string): Promise<void> {
|
|
if (import.meta.server) return
|
|
if (locale) setFormatLocale(locale, Intl.DateTimeFormat().resolvedOptions().timeZone)
|
|
if (!config.hostApiBase) {
|
|
console.error('vue-chat-layer: runtimeConfig.public.chat.hostApiBase is not set; the chat does not start')
|
|
return
|
|
}
|
|
const id = currentUserId()
|
|
if (id === null) {
|
|
// Signed out in this tab: forget the last session.
|
|
if (userId.value !== null) reset()
|
|
return
|
|
}
|
|
if (userId.value !== id) {
|
|
reset()
|
|
userId.value = id
|
|
}
|
|
if (!hasRealtimeAuth()) setRealtimeAuth(() => auth.token(), auth.refresh ? () => auth.refresh!() : undefined)
|
|
const gen = generation
|
|
await bootstrap()
|
|
if (gen !== generation || !member.value) return
|
|
void loadMembers()
|
|
watchVisibility()
|
|
void startRealtime()
|
|
}
|
|
|
|
/** Loads the latest page of a conversation. */
|
|
async function loadLatest(conversationId: number) {
|
|
const gen = generation
|
|
loading.value[conversationId] = true
|
|
errors.value[conversationId] = ''
|
|
try {
|
|
const page = await api.messages(conversationId, { limit: MESSAGE_PAGE })
|
|
if (gen !== generation) return
|
|
messages.value[conversationId] = page
|
|
reachedStart.value[conversationId] = page.length < MESSAGE_PAGE
|
|
// Nothing unread: what loaded is already read, so opening it sends no read.
|
|
if (unreadOf(conversationId) === 0 && mentionsOf(conversationId) === 0) readUpTo.set(conversationId, page.at(-1)?.id ?? 0)
|
|
} catch {
|
|
if (gen === generation) errors.value[conversationId] = 'error.load'
|
|
} finally {
|
|
if (gen === generation) loading.value[conversationId] = false
|
|
}
|
|
}
|
|
|
|
/** Makes a conversation active and loads its latest page once. */
|
|
async function open(conversationId: number, as: ChatKind) {
|
|
activeId.value = conversationId
|
|
kind.value = as
|
|
void syncOpenChannel()
|
|
if (messages.value[conversationId] === undefined && !loading.value[conversationId]) await loadLatest(conversationId)
|
|
}
|
|
|
|
/**
|
|
* Opens a channel: a channel the user left is joined again, and the
|
|
* conversation route runs once a session (it makes the caller a
|
|
* participant of the channel's conversation).
|
|
*/
|
|
async function openChannel(channel: ChatChannel): Promise<boolean> {
|
|
const ctx = context.value
|
|
const gen = generation
|
|
try {
|
|
if (!channel.joined && ctx) {
|
|
await api.joinChannel(ctx, channel.id)
|
|
if (gen !== generation) return false
|
|
const row = channels.value.find((c) => c.id === channel.id)
|
|
if (row) row.joined = true
|
|
}
|
|
if (!joinedConversations.has(channel.id)) {
|
|
await api.openConversation('channel', channel.id)
|
|
if (gen !== generation) return false
|
|
joinedConversations.add(channel.id)
|
|
}
|
|
} catch {
|
|
if (gen === generation) notice.show('error.openChannel')
|
|
return false
|
|
}
|
|
await open(channel.conversation_id, 'channel')
|
|
return true
|
|
}
|
|
|
|
/** Leaves a channel; it stays listed with joined false. */
|
|
async function leaveChannel(channel: ChatChannel): Promise<boolean> {
|
|
const ctx = context.value
|
|
if (!ctx) return false
|
|
try {
|
|
await api.leaveChannel(ctx, channel.id)
|
|
} catch {
|
|
notice.show('error.leaveChannel')
|
|
return false
|
|
}
|
|
const row = channels.value.find((c) => c.id === channel.id)
|
|
if (row) row.joined = false
|
|
if (activeId.value === channel.conversation_id) {
|
|
activeId.value = null
|
|
kind.value = null
|
|
void syncOpenChannel()
|
|
}
|
|
void bootstrap()
|
|
return true
|
|
}
|
|
|
|
/** Joins a channel without opening it. */
|
|
async function joinChannel(channel: ChatChannel): Promise<boolean> {
|
|
const ctx = context.value
|
|
if (!ctx) return false
|
|
try {
|
|
await api.joinChannel(ctx, channel.id)
|
|
} catch {
|
|
notice.show('error.joinChannel')
|
|
return false
|
|
}
|
|
const row = channels.value.find((c) => c.id === channel.id)
|
|
if (row) row.joined = true
|
|
void bootstrap()
|
|
return true
|
|
}
|
|
|
|
/** Closes the open conversation (the floating panel's back button). */
|
|
function close() {
|
|
activeId.value = null
|
|
kind.value = null
|
|
void syncOpenChannel()
|
|
}
|
|
|
|
/**
|
|
* Refetches the latest page and merges it (gap fill after a reconnect,
|
|
* polling without realtime). A page that no longer overlaps what is
|
|
* loaded replaces it, so the list never shows a hole. A loaded message
|
|
* the page should hold but no longer does was deleted while no event
|
|
* reached this client: it is shown as deleted, without its text.
|
|
*/
|
|
function refreshLatest(conversationId: number): Promise<void> {
|
|
const running = refreshing.get(conversationId)
|
|
if (running) return running
|
|
const gen = generation
|
|
const job = (async () => {
|
|
try {
|
|
const lastBefore = messages.value[conversationId]?.at(-1)?.id ?? 0
|
|
const page = await api.messages(conversationId, { limit: MESSAGE_PAGE })
|
|
if (gen !== generation) return
|
|
const old = messages.value[conversationId]
|
|
const lastOld = old?.at(-1)?.id ?? 0
|
|
if (!old || (page.length >= MESSAGE_PAGE && page[0].id > lastOld)) {
|
|
messages.value[conversationId] = page
|
|
errors.value[conversationId] = ''
|
|
reachedStart.value[conversationId] = page.length < MESSAGE_PAGE
|
|
return
|
|
}
|
|
markMissingDeleted(old, page, lastBefore)
|
|
const byId = new Map(old.map((m) => [m.id, m]))
|
|
for (const m of page) byId.set(m.id, m)
|
|
messages.value[conversationId] = [...byId.values()].sort((a, b) => a.id - b.id)
|
|
} catch {
|
|
/* the next event or poll tries again */
|
|
} finally {
|
|
if (gen === generation) refreshing.delete(conversationId)
|
|
}
|
|
})()
|
|
refreshing.set(conversationId, job)
|
|
return job
|
|
}
|
|
|
|
/** The previous page before the oldest loaded message. */
|
|
async function loadOlder(conversationId: number) {
|
|
const list = messages.value[conversationId]
|
|
if (!list?.length || olderLoading.value[conversationId] || reachedStart.value[conversationId]) return
|
|
const gen = generation
|
|
olderLoading.value[conversationId] = true
|
|
olderError.value[conversationId] = ''
|
|
try {
|
|
const page = await api.messages(conversationId, { limit: MESSAGE_PAGE, before: list[0].id })
|
|
if (gen !== generation) return
|
|
const current = messages.value[conversationId] ?? []
|
|
const known = new Set(current.map((m) => m.id))
|
|
messages.value[conversationId] = [...page.filter((m) => !known.has(m.id)), ...current]
|
|
reachedStart.value[conversationId] = page.length < MESSAGE_PAGE
|
|
} catch {
|
|
if (gen === generation) olderError.value[conversationId] = 'error.older'
|
|
} finally {
|
|
if (gen === generation) olderLoading.value[conversationId] = false
|
|
}
|
|
}
|
|
|
|
function zeroLocal(conversationId: number) {
|
|
const ch = channelOf(conversationId)
|
|
if (ch) {
|
|
ch.unread = 0
|
|
ch.mentions = 0
|
|
return
|
|
}
|
|
const row = conversations.value.find((c) => c.id === conversationId)
|
|
if (row) row.unread = 0
|
|
}
|
|
|
|
/**
|
|
* Called when the conversation is seen (the message list checks the rule).
|
|
* The badges drop at once; the POST goes out once per 500 ms window, and
|
|
* only when something is unread or newer than the last read.
|
|
*/
|
|
function markRead(conversationId: number) {
|
|
const last = messages.value[conversationId]?.at(-1)?.id ?? 0
|
|
const pending = unreadOf(conversationId) > 0 || mentionsOf(conversationId) > 0 || last > (readUpTo.get(conversationId) ?? 0)
|
|
if (!pending) return
|
|
zeroLocal(conversationId)
|
|
readUpTo.set(conversationId, last)
|
|
if (readTimers.has(conversationId)) return
|
|
const gen = generation
|
|
readTimers.set(
|
|
conversationId,
|
|
setTimeout(() => {
|
|
readTimers.delete(conversationId)
|
|
if (gen !== generation) return
|
|
readInFlight.add(conversationId)
|
|
api
|
|
.markRead(conversationId)
|
|
.catch(() => {
|
|
/* the next bootstrap corrects the count */
|
|
})
|
|
.finally(() => {
|
|
if (gen === generation) readInFlight.delete(conversationId)
|
|
})
|
|
}, READ_DEBOUNCE_MS),
|
|
)
|
|
}
|
|
|
|
/** Counts are refetched whenever the page becomes visible again (other tabs and devices read too). */
|
|
function watchVisibility() {
|
|
if (onVisibility || typeof document === 'undefined') return
|
|
onVisibility = () => {
|
|
if (document.visibilityState === 'visible' && member.value) void refetchCounts()
|
|
}
|
|
document.addEventListener('visibilitychange', onVisibility)
|
|
}
|
|
|
|
/** The user is looking at the conversation: active, on screen, window focused. */
|
|
function seen(conversationId: number): boolean {
|
|
return activeId.value === conversationId && panelVisible.value && pageFocused()
|
|
}
|
|
|
|
function appendMessage(m: ChatMessage) {
|
|
if (m.root_id) return
|
|
const list = messages.value[m.conversation_id]
|
|
if (list) insertMessage(list, m)
|
|
const row = conversations.value.find((c) => c.id === m.conversation_id)
|
|
if (row && (!row.last_message || Date.parse(m.created_at) >= Date.parse(row.last_message.created_at))) {
|
|
row.last_message = { id: m.id, sender_id: m.sender_id, content: m.content ?? '', created_at: m.created_at }
|
|
}
|
|
}
|
|
|
|
/** Opens one DM. */
|
|
async function openDm(conversationId: number) {
|
|
dmError.value = ''
|
|
await open(conversationId, 'dm')
|
|
}
|
|
|
|
/** The DM row with a member, if the user already has one. */
|
|
function dmWith(otherUserId: number): ChatConversationRow | undefined {
|
|
return conversations.value.find((c) => c.other_user_id === otherUserId)
|
|
}
|
|
|
|
/**
|
|
* Opens the DM with a member, creating it through golem15.chat when it is
|
|
* new. Returns the conversation id, or null with dmError set.
|
|
*/
|
|
async function startDm(otherUserId: number): Promise<number | null> {
|
|
dmError.value = ''
|
|
const existing = dmWith(otherUserId)
|
|
if (existing) {
|
|
await openDm(existing.id)
|
|
return existing.id
|
|
}
|
|
const ctx = context.value
|
|
if (!ctx) return null
|
|
const gen = generation
|
|
try {
|
|
const conv = await api.startDm(ctx, otherUserId)
|
|
if (gen !== generation) return null
|
|
if (!conversations.value.some((c) => c.id === conv.id)) {
|
|
conversations.value.unshift({ id: conv.id, type: conv.type || 'dm', other_user_id: otherUserId, unread: 0, last_message: null })
|
|
}
|
|
await openDm(conv.id)
|
|
return conv.id
|
|
} catch (e) {
|
|
if (gen === generation) dmError.value = dmErrorKey(e)
|
|
return null
|
|
}
|
|
}
|
|
|
|
function draft(conversationId: number | null): Readonly<ChatDraft> {
|
|
return (conversationId !== null && drafts.value[conversationId]) || EMPTY_DRAFT
|
|
}
|
|
|
|
function ensureDraft(conversationId: number): ChatDraft {
|
|
if (!drafts.value[conversationId]) drafts.value[conversationId] = { text: '', error: '', detail: '', sending: false }
|
|
return drafts.value[conversationId]
|
|
}
|
|
|
|
/** Text and no send in flight. */
|
|
function canSend(conversationId: number | null): boolean {
|
|
const d = draft(conversationId)
|
|
if (d.sending) return false
|
|
return d.text.trim() !== ''
|
|
}
|
|
|
|
function setDraftText(conversationId: number, text: string) {
|
|
const d = ensureDraft(conversationId)
|
|
d.text = text
|
|
d.error = ''
|
|
d.detail = ''
|
|
}
|
|
|
|
/**
|
|
* Sends the draft of a conversation (the open one by default). No
|
|
* optimistic row: the message appears once the API answers. On failure
|
|
* the draft is kept and the error line set.
|
|
*/
|
|
async function send(conversationId: number | null = activeId.value): Promise<boolean> {
|
|
if (conversationId === null) return false
|
|
const d = ensureDraft(conversationId)
|
|
const content = d.text.trim()
|
|
if (!content || d.sending) return false
|
|
const body: ChatSendBody = { content }
|
|
d.sending = true
|
|
d.error = ''
|
|
d.detail = ''
|
|
const gen = generation
|
|
try {
|
|
const m = await api.send(conversationId, body)
|
|
if (gen !== generation) return false
|
|
appendMessage(m)
|
|
d.text = ''
|
|
return true
|
|
} catch (e) {
|
|
if (gen !== generation) return false
|
|
d.error = sendErrorKey(e)
|
|
if (e instanceof ChatApiError) d.detail = e.field('content')
|
|
if (e instanceof ChatApiError && (e.status === 403 || e.status === 404)) void bootstrap()
|
|
return false
|
|
} finally {
|
|
d.sending = false
|
|
}
|
|
}
|
|
|
|
function saveAnchor(conversationId: number, anchor: ChatAnchor) {
|
|
anchors.value[conversationId] = { ...anchor }
|
|
}
|
|
|
|
function anchorFor(conversationId: number): ChatAnchor | null {
|
|
return anchors.value[conversationId] ?? null
|
|
}
|
|
|
|
/** The member list, once per session. */
|
|
function loadMembers(force = false): Promise<void> {
|
|
if (membersLoading) return membersLoading
|
|
if (membersState.value === 'ready' && !force) return Promise.resolve()
|
|
const gen = generation
|
|
membersState.value = 'loading'
|
|
membersLoading = (async () => {
|
|
try {
|
|
const list = await api.members()
|
|
if (gen !== generation) return
|
|
memberRows.value = Object.fromEntries(list.map((m) => [m.id, m]))
|
|
membersState.value = 'ready'
|
|
} catch {
|
|
if (gen === generation) membersState.value = 'error'
|
|
} finally {
|
|
if (gen === generation) membersLoading = null
|
|
}
|
|
})()
|
|
return membersLoading
|
|
}
|
|
|
|
/** The loaded copy of a message, if any. */
|
|
function findMessage(conversationId: number, id: number): ChatMessage | undefined {
|
|
return messages.value[conversationId]?.find((m) => m.id === id)
|
|
}
|
|
|
|
/** A newer copy of a message (an edit), also in the DM row preview. */
|
|
function replaceMessage(next: ChatMessage) {
|
|
const list = messages.value[next.conversation_id]
|
|
const i = list ? list.findIndex((m) => m.id === next.id) : -1
|
|
if (list && i >= 0) list[i] = next
|
|
const row = conversations.value.find((c) => c.id === next.conversation_id)
|
|
if (row?.last_message?.id === next.id) row.last_message = { ...row.last_message, content: next.content ?? '' }
|
|
}
|
|
|
|
/** Marks a loaded message deleted and blanks its DM preview. */
|
|
function deleteLocal(conversationId: number, id: number) {
|
|
const m = findMessage(conversationId, id)
|
|
if (m) markDeleted(m)
|
|
const row = conversations.value.find((c) => c.id === conversationId)
|
|
if (row?.last_message?.id === id) row.last_message = { ...row.last_message, content: '' }
|
|
}
|
|
|
|
/** updated.chat.message: refetch a loaded message (events carry ids only). */
|
|
async function refetchMessage(conversationId: number, id: number) {
|
|
if (!findMessage(conversationId, id)) return
|
|
const gen = generation
|
|
try {
|
|
const m = await api.message(id)
|
|
if (gen !== generation) return
|
|
if (m.deleted_at) deleteLocal(conversationId, id)
|
|
else replaceMessage(m)
|
|
} catch {
|
|
/* the next gap fill brings it */
|
|
}
|
|
}
|
|
|
|
/** Refetches the bootstrap counts; a failure keeps the last values. */
|
|
function refetchCounts(): Promise<void> {
|
|
return bootstrap()
|
|
}
|
|
|
|
/** A content-free created event: fetch the message over REST, once per id. */
|
|
async function fetchMessage(id: number) {
|
|
if (fetchingIds.has(id)) return
|
|
fetchingIds.add(id)
|
|
const gen = generation
|
|
try {
|
|
const m = await api.message(id)
|
|
if (gen === generation) appendMessage(m)
|
|
} catch {
|
|
/* the next gap fill or poll brings it */
|
|
} finally {
|
|
if (gen === generation) fetchingIds.delete(id)
|
|
}
|
|
}
|
|
|
|
/** A message from someone else on user:{me}: counts, preview, order and new DM rows. */
|
|
function receiveMessage(m: ChatMessage) {
|
|
const conv = m.conversation_id
|
|
stopTyping(conv, m.sender_id)
|
|
const isSeen = seen(conv)
|
|
if (!m.root_id) {
|
|
const list = messages.value[conv]
|
|
if (list) insertMessage(list, m)
|
|
}
|
|
const ch = channelOf(conv)
|
|
if (ch) {
|
|
if (!isSeen) ch.unread += 1
|
|
return
|
|
}
|
|
conversations.value = applyChatMessage(conversations.value, m, { seen: isSeen })
|
|
}
|
|
|
|
function handleEvent(ev: ChatEvent) {
|
|
switch (ev.kind) {
|
|
case 'created':
|
|
stopTyping(ev.conversationId, ev.senderId)
|
|
if (!ev.rootId && needsFetch(ev, messages.value)) void fetchMessage(ev.id)
|
|
return
|
|
case 'typing':
|
|
onTyping(ev.conversationId, ev.userId)
|
|
return
|
|
case 'chatMessage':
|
|
receiveMessage(ev.message)
|
|
return
|
|
case 'mentions':
|
|
void refetchCounts()
|
|
return
|
|
case 'updated':
|
|
void refetchMessage(ev.conversationId, ev.id)
|
|
return
|
|
case 'deleted':
|
|
deleteLocal(ev.conversationId, ev.id)
|
|
return
|
|
default:
|
|
return
|
|
}
|
|
}
|
|
|
|
function onPublication(data: unknown) {
|
|
const ev = parsePublication(data)
|
|
if (ev) handleEvent(ev)
|
|
}
|
|
|
|
/** user:{me}: the chat's own events, everything else to onUserEvent handlers. */
|
|
function onUserPublication(data: unknown) {
|
|
const ev = parsePublication(data)
|
|
if (ev) handleEvent(ev)
|
|
else dispatchUserEvent(data)
|
|
}
|
|
|
|
/**
|
|
* History and recovery are off, so every (re)subscribe refetches the open
|
|
* conversation's latest page and the counts.
|
|
*/
|
|
function gapFill() {
|
|
const id = activeId.value
|
|
if (id !== null && messages.value[id] !== undefined) void refreshLatest(id)
|
|
void refetchCounts()
|
|
}
|
|
|
|
function onConnectionState(s: ConnectionState) {
|
|
if (connection.value === 'idle' || connection.value === 'unavailable') return
|
|
if (s === 'connected') {
|
|
connection.value = 'connected'
|
|
return
|
|
}
|
|
// Presence and typing come back with the next subscribe.
|
|
presenceAvailable.value = false
|
|
clearTyping()
|
|
connection.value = connection.value === 'connected' || connection.value === 'reconnecting' ? 'reconnecting' : 'connecting'
|
|
}
|
|
|
|
function startPolling() {
|
|
stopPolling()
|
|
activePoll = setInterval(() => {
|
|
const id = activeId.value
|
|
if (id !== null) void refreshLatest(id)
|
|
}, POLL_ACTIVE_MS)
|
|
countsPoll = setInterval(() => void refetchCounts(), POLL_COUNTS_MS)
|
|
}
|
|
|
|
function stopPolling() {
|
|
if (activePoll) clearInterval(activePoll)
|
|
if (countsPoll) clearInterval(countsPoll)
|
|
activePoll = null
|
|
countsPoll = null
|
|
}
|
|
|
|
/** No live updates for this session: say so and poll. */
|
|
function goUnavailable() {
|
|
if (!realtimeStarted || connection.value === 'unavailable') return
|
|
connection.value = 'unavailable'
|
|
presenceAvailable.value = false
|
|
clearTyping()
|
|
startPolling()
|
|
}
|
|
|
|
function onTyping(conversationId: number, user: number) {
|
|
if (user === userId.value || connection.value === 'unavailable') return
|
|
const current = typing.value[conversationId] ?? []
|
|
if (!current.includes(user)) typing.value[conversationId] = [...current, user]
|
|
const key = `${conversationId}:${user}`
|
|
const old = typingTimers.get(key)
|
|
if (old) clearTimeout(old)
|
|
typingTimers.set(
|
|
key,
|
|
setTimeout(() => stopTyping(conversationId, user), TYPING_EXPIRY_MS),
|
|
)
|
|
}
|
|
|
|
function stopTyping(conversationId: number, user: number) {
|
|
const key = `${conversationId}:${user}`
|
|
const t = typingTimers.get(key)
|
|
if (t) clearTimeout(t)
|
|
typingTimers.delete(key)
|
|
const current = typing.value[conversationId]
|
|
if (current?.includes(user)) typing.value[conversationId] = current.filter((x) => x !== user)
|
|
}
|
|
|
|
function clearTyping() {
|
|
for (const t of typingTimers.values()) clearTimeout(t)
|
|
typingTimers.clear()
|
|
typing.value = {}
|
|
}
|
|
|
|
/** The composer tells the others, at most once every 3 s, never for blank text. */
|
|
function emitTyping(conversationId: number, text: string) {
|
|
if (!text.trim() || connection.value === 'idle' || connection.value === 'unavailable') return
|
|
const now = Date.now()
|
|
const last = typingSentAt.get(conversationId)
|
|
if (last !== undefined && now - last < TYPING_THROTTLE_MS) return
|
|
typingSentAt.set(conversationId, now)
|
|
api.typing(conversationId).catch(() => {
|
|
/* typing is best effort */
|
|
})
|
|
}
|
|
|
|
/** The open channel's presence after every subscribe; null from the client means hidden. */
|
|
async function loadPresence(channel: string) {
|
|
const gen = generation
|
|
const got = await fetchPresence(channel)
|
|
if (gen !== generation || connection.value === 'unavailable') return
|
|
if (got === null) {
|
|
presenceAvailable.value = false
|
|
return
|
|
}
|
|
presenceClients.value = new Map(got.map((p) => [p.client, p.user]))
|
|
presenceAvailable.value = true
|
|
}
|
|
|
|
function onJoin(who: PresenceClient) {
|
|
const next = new Map(presenceClients.value)
|
|
next.set(who.client, who.user)
|
|
presenceClients.value = next
|
|
}
|
|
|
|
function onLeave(who: PresenceClient) {
|
|
if (!presenceClients.value.has(who.client)) return
|
|
const next = new Map(presenceClients.value)
|
|
next.delete(who.client)
|
|
presenceClients.value = next
|
|
}
|
|
|
|
/** Connects once per member session: user:{me} on the shared client, then the open conversation. */
|
|
async function startRealtime() {
|
|
if (realtimeStarted || userId.value === null) return
|
|
realtimeStarted = true
|
|
const gen = generation
|
|
const me = userId.value
|
|
connection.value = 'connecting'
|
|
unlisten.push(onConnection(onConnectionState), onUnavailable(goUnavailable))
|
|
try {
|
|
const u = await subscribe(`user:${me}`, { onPublication: onUserPublication, onSubscribed: gapFill })
|
|
if (gen !== generation) return u.close()
|
|
userHandle = u
|
|
await syncOpenChannel()
|
|
} catch {
|
|
// The client chunk did not load: the chat still works over REST.
|
|
if (gen === generation) goUnavailable()
|
|
}
|
|
}
|
|
|
|
/** Subscribes the open conversation's channel and leaves the previous one. */
|
|
async function syncOpenChannel() {
|
|
if (!realtimeStarted) return
|
|
const want = activeId.value
|
|
if (want === openChannelId) return
|
|
const seq = ++openSeq
|
|
openHandle?.close()
|
|
openHandle = null
|
|
openChannelId = want
|
|
presenceAvailable.value = false
|
|
presenceClients.value = new Map()
|
|
if (want === null) return
|
|
const gen = generation
|
|
const name = conversationChannel(want)
|
|
const withPresence = kind.value === 'channel'
|
|
try {
|
|
const h = await subscribe(name, {
|
|
onPublication,
|
|
onSubscribed: () => {
|
|
gapFill()
|
|
if (withPresence) void loadPresence(name)
|
|
},
|
|
onJoin: withPresence ? onJoin : undefined,
|
|
onLeave: withPresence ? onLeave : undefined,
|
|
})
|
|
if (gen !== generation || seq !== openSeq) return h.close()
|
|
openHandle = h
|
|
} catch {
|
|
/* goUnavailable already ran for the client */
|
|
}
|
|
}
|
|
|
|
/** Closes the chat's handles and listeners; returns whether realtime had started. */
|
|
function stopRealtime(): boolean {
|
|
for (const off of unlisten) off()
|
|
unlisten = []
|
|
userHandle?.close()
|
|
openHandle?.close()
|
|
userHandle = openHandle = null
|
|
openChannelId = null
|
|
openSeq++
|
|
stopPolling()
|
|
const was = realtimeStarted
|
|
realtimeStarted = false
|
|
connection.value = 'idle'
|
|
presenceAvailable.value = false
|
|
presenceClients.value = new Map()
|
|
clearTyping()
|
|
typingSentAt.clear()
|
|
return was
|
|
}
|
|
|
|
/** Forgets everything: on logout a second account never sees the first one's chat. */
|
|
function reset() {
|
|
// The socket carries this user's token: drop it, the next login gets a fresh one.
|
|
if (stopRealtime() || userId.value !== null) disconnectRealtime()
|
|
fetchingIds.clear()
|
|
refreshing.clear()
|
|
for (const t of readTimers.values()) clearTimeout(t)
|
|
readTimers.clear()
|
|
readInFlight.clear()
|
|
readUpTo.clear()
|
|
joinedConversations.clear()
|
|
if (onVisibility && typeof document !== 'undefined') document.removeEventListener('visibilitychange', onVisibility)
|
|
onVisibility = null
|
|
generation++
|
|
bootstrapping = null
|
|
membersLoading = null
|
|
userId.value = null
|
|
member.value = undefined
|
|
moderator.value = false
|
|
context.value = null
|
|
channels.value = []
|
|
conversations.value = []
|
|
limits.value = null
|
|
activeId.value = null
|
|
kind.value = null
|
|
dmError.value = ''
|
|
messages.value = {}
|
|
loading.value = {}
|
|
errors.value = {}
|
|
drafts.value = {}
|
|
anchors.value = {}
|
|
reachedStart.value = {}
|
|
olderLoading.value = {}
|
|
olderError.value = {}
|
|
memberRows.value = {}
|
|
membersState.value = 'idle'
|
|
bootstrapState.value = 'idle'
|
|
}
|
|
|
|
return reactive({
|
|
userId,
|
|
member,
|
|
moderator,
|
|
context,
|
|
channels,
|
|
joinedChannels,
|
|
activeChannel,
|
|
activeDm,
|
|
conversations,
|
|
limits,
|
|
activeId,
|
|
kind,
|
|
dmError,
|
|
dmRows,
|
|
messages,
|
|
loading,
|
|
errors,
|
|
drafts,
|
|
anchors,
|
|
members,
|
|
membersByHandle,
|
|
myHandle,
|
|
membersState,
|
|
bootstrapState,
|
|
connection,
|
|
panelVisible,
|
|
reachedStart,
|
|
olderLoading,
|
|
olderError,
|
|
dmUnread,
|
|
channelUnread,
|
|
totalMentions,
|
|
attention,
|
|
unreadOf,
|
|
mentionsOf,
|
|
isChannel,
|
|
markRead,
|
|
loadOlder,
|
|
presenceAvailable,
|
|
othersOnline,
|
|
onlineCount,
|
|
isOnline,
|
|
typing,
|
|
typingIn,
|
|
emitTyping,
|
|
start,
|
|
bootstrap,
|
|
open,
|
|
openChannel,
|
|
joinChannel,
|
|
leaveChannel,
|
|
close,
|
|
openDm,
|
|
dmWith,
|
|
startDm,
|
|
loadLatest,
|
|
refreshLatest,
|
|
refetchCounts,
|
|
draft,
|
|
setDraftText,
|
|
canSend,
|
|
send,
|
|
saveAnchor,
|
|
anchorFor,
|
|
loadMembers,
|
|
findMessage,
|
|
replaceMessage,
|
|
deleteLocal,
|
|
reset,
|
|
})
|
|
}
|
|
|
|
export type ChatStore = ReturnType<typeof createChatStore>
|
|
|
|
/** The app's chat store (one per Nuxt app). */
|
|
export function useChat(): ChatStore {
|
|
const nuxtApp = useNuxtApp() as unknown as { _chatStore?: ChatStore }
|
|
if (!nuxtApp._chatStore) nuxtApp._chatStore = createChatStore()
|
|
return nuxtApp._chatStore
|
|
}
|