From 5d581539b30955bb20de37cf18d5f5d62d123a8d Mon Sep 17 00:00:00 2001 From: Jakub Zych Date: Sat, 31 Oct 2026 13:52:56 +0100 Subject: [PATCH] feat: port the chat store, realtime client and components - 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 --- app/components/Chat/Avatar.vue | 20 + app/components/Chat/ChannelList.vue | 57 +- app/components/Chat/Composer.vue | 227 +++++- app/components/Chat/DmList.vue | 78 ++ app/components/Chat/Header.vue | 94 +++ app/components/Chat/Icon.vue | 34 + app/components/Chat/MemberPicker.vue | 94 +++ app/components/Chat/MentionPopup.vue | 38 + app/components/Chat/Message.vue | 49 ++ app/components/Chat/MessageList.vue | 301 ++++++- app/components/Chat/Notices.vue | 14 + app/components/Chat/Page.vue | 49 +- app/components/Chat/Panel.vue | 69 ++ app/composables/useChat.ts | 1128 +++++++++++++++++++++++++- app/composables/useChatNotice.ts | 26 + app/lib/chatEvents.ts | 186 +++++ app/lib/chatFormat.ts | 138 ++++ app/lib/chatText.ts | 143 ++++ app/lib/chatUnread.ts | 64 ++ app/lib/client.ts | 40 +- app/lib/format.ts | 89 ++ app/lib/markdown.ts | 32 + app/lib/media.ts | 20 + app/lib/realtime.ts | 417 ++++++++++ app/lib/tabs.ts | 19 + i18n/locales/en.json | 91 ++- i18n/locales/pl.json | 91 ++- 27 files changed, 3516 insertions(+), 92 deletions(-) create mode 100644 app/components/Chat/Avatar.vue create mode 100644 app/components/Chat/DmList.vue create mode 100644 app/components/Chat/Header.vue create mode 100644 app/components/Chat/Icon.vue create mode 100644 app/components/Chat/MemberPicker.vue create mode 100644 app/components/Chat/MentionPopup.vue create mode 100644 app/components/Chat/Message.vue create mode 100644 app/components/Chat/Notices.vue create mode 100644 app/components/Chat/Panel.vue create mode 100644 app/composables/useChatNotice.ts create mode 100644 app/lib/chatEvents.ts create mode 100644 app/lib/chatFormat.ts create mode 100644 app/lib/chatText.ts create mode 100644 app/lib/chatUnread.ts create mode 100644 app/lib/format.ts create mode 100644 app/lib/markdown.ts create mode 100644 app/lib/media.ts create mode 100644 app/lib/realtime.ts create mode 100644 app/lib/tabs.ts diff --git a/app/components/Chat/Avatar.vue b/app/components/Chat/Avatar.vue new file mode 100644 index 0000000..b28f467 --- /dev/null +++ b/app/components/Chat/Avatar.vue @@ -0,0 +1,20 @@ + + + diff --git a/app/components/Chat/ChannelList.vue b/app/components/Chat/ChannelList.vue index f367cba..3916403 100644 --- a/app/components/Chat/ChannelList.vue +++ b/app/components/Chat/ChannelList.vue @@ -1,25 +1,62 @@ diff --git a/app/components/Chat/Composer.vue b/app/components/Chat/Composer.vue index 1b74e41..686426b 100644 --- a/app/components/Chat/Composer.vue +++ b/app/components/Chat/Composer.vue @@ -1,28 +1,237 @@ diff --git a/app/components/Chat/DmList.vue b/app/components/Chat/DmList.vue new file mode 100644 index 0000000..e43d26c --- /dev/null +++ b/app/components/Chat/DmList.vue @@ -0,0 +1,78 @@ + + + diff --git a/app/components/Chat/Header.vue b/app/components/Chat/Header.vue new file mode 100644 index 0000000..afa3866 --- /dev/null +++ b/app/components/Chat/Header.vue @@ -0,0 +1,94 @@ + + + diff --git a/app/components/Chat/Icon.vue b/app/components/Chat/Icon.vue new file mode 100644 index 0000000..f10ed28 --- /dev/null +++ b/app/components/Chat/Icon.vue @@ -0,0 +1,34 @@ + + + diff --git a/app/components/Chat/MemberPicker.vue b/app/components/Chat/MemberPicker.vue new file mode 100644 index 0000000..ec7577f --- /dev/null +++ b/app/components/Chat/MemberPicker.vue @@ -0,0 +1,94 @@ + + + diff --git a/app/components/Chat/MentionPopup.vue b/app/components/Chat/MentionPopup.vue new file mode 100644 index 0000000..4cdc772 --- /dev/null +++ b/app/components/Chat/MentionPopup.vue @@ -0,0 +1,38 @@ + + + diff --git a/app/components/Chat/Message.vue b/app/components/Chat/Message.vue new file mode 100644 index 0000000..a069a0e --- /dev/null +++ b/app/components/Chat/Message.vue @@ -0,0 +1,49 @@ + + + diff --git a/app/components/Chat/MessageList.vue b/app/components/Chat/MessageList.vue index d94066d..95b8367 100644 --- a/app/components/Chat/MessageList.vue +++ b/app/components/Chat/MessageList.vue @@ -1,16 +1,301 @@ diff --git a/app/components/Chat/Notices.vue b/app/components/Chat/Notices.vue new file mode 100644 index 0000000..4253554 --- /dev/null +++ b/app/components/Chat/Notices.vue @@ -0,0 +1,14 @@ + + + diff --git a/app/components/Chat/Page.vue b/app/components/Chat/Page.vue index d1fe0ea..59892e2 100644 --- a/app/components/Chat/Page.vue +++ b/app/components/Chat/Page.vue @@ -1,26 +1,45 @@ diff --git a/app/components/Chat/Panel.vue b/app/components/Chat/Panel.vue new file mode 100644 index 0000000..6bbe1ff --- /dev/null +++ b/app/components/Chat/Panel.vue @@ -0,0 +1,69 @@ + + + diff --git a/app/composables/useChat.ts b/app/composables/useChat.ts index a1aae73..ded73c7 100644 --- a/app/composables/useChat.ts +++ b/app/composables/useChat.ts @@ -1,72 +1,1118 @@ -// 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 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' -/** The fallback page size of the message list. */ +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 -export function useChat() { +const EMPTY_DRAFT: Readonly = 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() - /** undefined: not known yet; false: outside the community. */ + const userId = useState('chat:userId', () => null) + /** undefined: not known yet (bootstrap in flight). */ const member = useState('chat:member', () => undefined) + const moderator = useState('chat:moderator', () => false) + const context = useState<{ type: string; id: number } | null>('chat:context', () => null) const channels = useState('chat:channels', () => []) + const conversations = useState('chat:conversations', () => []) + const limits = useState('chat:limits', () => null) /** The open conversation id. */ const activeId = useState('chat:activeId', () => null) + const kind = useState('chat:kind', () => null) + const dmError = useState('chat:dmError', () => '') + /** Messages per conversation id, oldest first; absent until loaded. */ const messages = useState>('chat:messages', () => ({})) - const drafts = useState>('chat:drafts', () => ({})) - const error = useState('chat:error', () => '') - const sending = useState('chat:sending', () => false) + const loading = useState>('chat:loading', () => ({})) + const errors = useState>('chat:errors', () => ({})) + const drafts = useState>('chat:drafts', () => ({})) + const anchors = useState>('chat:anchors', () => ({})) + /** Members by id (the others; the caller is not listed). */ + const memberRows = useState>('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('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>('chat:reachedStart', () => ({})) + const olderLoading = useState>('chat:olderLoading', () => ({})) + const olderError = useState>('chat:olderError', () => ({})) + /** Who is typing, per conversation (others only). */ + const typing = useState>('chat:typing', () => ({})) + /** Presence of the open channel: Centrifugo client id to user id. */ + const presenceClients = shallowRef>(new Map()) + const presenceAvailable = ref(false) - /** Loads the bootstrap; without public.chat.hostApiBase it logs an error and stops. */ - async function start(): Promise { + /** Bumped by reset(): answers of an older session are dropped. */ + let generation = 0 + let bootstrapping: Promise | null = null + let membersLoading: Promise | null = null + /** Channels whose conversation route ran this session (it makes the caller a participant). */ + const joinedConversations = new Set() + + // 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 | null = null + let countsPoll: ReturnType | null = null + const fetchingIds = new Set() + const refreshing = new Map>() + // Read marking: the newest message id already marked, the debounce timers, POSTs in flight. + const readUpTo = new Map() + const readTimers = new Map>() + const readInFlight = new Set() + let onVisibility: (() => void) | null = null + const typingTimers = new Map>() + const typingSentAt = new Map() + + 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() + 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>) { + 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 { + 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 { + 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 b = await api.bootstrap() - if (!b.member) { - member.value = false - channels.value = [] - return - } - member.value = true - channels.value = b.channels.map((c) => ({ ...c })) + 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 { - error.value = 'bootstrap' + if (gen === generation) errors.value[conversationId] = 'error.load' + } finally { + if (gen === generation) loading.value[conversationId] = false } } - /** 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 }) + /** 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) } - /** 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 + /** + * 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 { + const ctx = context.value + const gen = generation 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 + 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 { - error.value = 'send' + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { - sending.value = false + d.sending = false } } - return { member, channels, activeId, messages, drafts, error, sending, start, open, send } + 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 { + 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 { + 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 + +/** 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 } diff --git a/app/composables/useChatNotice.ts b/app/composables/useChatNotice.ts new file mode 100644 index 0000000..07cecd9 --- /dev/null +++ b/app/composables/useChatNotice.ts @@ -0,0 +1,26 @@ +// The chat's short notices (a failed reaction, a refused pin, a download +// error): one message at a time, gone after a few seconds. ChatNotices +// renders it inside ChatPage and the floating panel. The message is an i18n +// key under chat. with optional parameters. +export interface ChatNotice { + key: string + params?: Record +} + +export function useChatNotice() { + const current = useState('chat:notice', () => null) + const nuxtApp = useNuxtApp() as unknown as { _chatNoticeTimer?: ReturnType } + + function show(key: string, params?: Record, ms = 4000) { + current.value = { key, params } + clearTimeout(nuxtApp._chatNoticeTimer) + nuxtApp._chatNoticeTimer = setTimeout(() => (current.value = null), ms) + } + + function clear() { + clearTimeout(nuxtApp._chatNoticeTimer) + current.value = null + } + + return { current, show, clear } +} diff --git a/app/lib/chatEvents.ts b/app/lib/chatEvents.ts new file mode 100644 index 0000000..5c899e1 --- /dev/null +++ b/app/lib/chatEvents.ts @@ -0,0 +1,186 @@ +// 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 +} diff --git a/app/lib/chatFormat.ts b/app/lib/chatFormat.ts new file mode 100644 index 0000000..365b64c --- /dev/null +++ b/app/lib/chatFormat.ts @@ -0,0 +1,138 @@ +// Names, initials, day separators, grouping and member search for the chat, +// ported from a Golem15 SPA's chatFormat.ts. The copy (today, yesterday, +// unknown person, "and N others") defaults to the SPA's Polish and is passed +// in localized by the layer's components. +import type { ChatMember, ChatMessage } from './types' +import { dayKey, daysUntil, fmtDay, formatLocale } from './format' + +type NameParts = Pick & { is_bot?: boolean } + +/** The local part of an e-mail address, or the text itself. */ +function localPart(s: string): string { + const at = s.indexOf('@') + return at > 0 ? s.slice(0, at) : s +} + +/** + * "Ola K.": name and the surname's initial; a bot is its name only. Falls + * back to @handle, then to the local part of the fallback (an e-mail address + * or a name from elsewhere). + */ +export function shortName(member: NameParts | undefined | null, fallback = '', unknown = 'Nieznana osoba'): string { + const name = member?.name?.trim() ?? '' + const surname = member?.surname?.trim() ?? '' + if (name && member?.is_bot) return name + if (name && surname) return `${name} ${surname[0]}.` + if (name) return name + if (member?.handle) return `@${member.handle}` + const f = fallback.trim() + return f ? localPart(f) : unknown +} + +/** The full name, for picker rows. */ +export function fullName(member: NameParts | undefined | null, fallback = ''): string { + const full = [member?.name?.trim(), member?.surname?.trim()].filter(Boolean).join(' ') + return full || shortName(member, fallback) +} + +/** "OK" from name and surname, else the first two letters of the handle. */ +export function initials(member: NameParts | undefined | null, fallback = ''): string { + const name = member?.name?.trim() ?? '' + const surname = member?.surname?.trim() ?? '' + let s = '' + if (name || surname) s = name.slice(0, 1) + surname.slice(0, 1) + else if (member?.handle) s = member.handle.slice(0, 2) + else s = localPart(fallback.trim()).slice(0, 2) + return (s || '?').toLocaleUpperCase(formatLocale()) +} + +/** The avatar palette slot --av-1 … --av-8 of a user. */ +export function avatarIndex(userId: number): number { + return (Math.abs(Math.trunc(userId)) % 8) + 1 +} + +/** The words of the day separators. */ +export interface DayLabels { + today: string + yesterday: string +} + +const PL_DAYS: DayLabels = { today: 'DZIŚ', yesterday: 'WCZORAJ' } + +/** DZIŚ, WCZORAJ or the uppercased day ("PONIEDZIAŁEK, 26 PAŹDZIERNIKA", with the year when it differs). */ +export function dayLabel(iso: string, now: Date = new Date(), labels: DayLabels = PL_DAYS): string { + const d = daysUntil(iso, now) + if (d === 0) return labels.today.toLocaleUpperCase(formatLocale()) + if (d === -1) return labels.yesterday.toLocaleUpperCase(formatLocale()) + const year = dayKey(iso).slice(0, 4) + const label = year === dayKey(now).slice(0, 4) ? fmtDay(iso) : `${fmtDay(iso)} ${year}` + return label.toLocaleUpperCase(formatLocale()) +} + +export type ChatListItem = + | { kind: 'day'; key: string; label: string } + | { kind: 'message'; key: string; message: ChatMessage; followUp: boolean } + +/** Messages by one author within this window, on one day, collapse. */ +export const GROUP_WINDOW_MS = 5 * 60 * 1000 + +/** Day separators and grouping for a list of messages, oldest first. */ +export function groupMessages(messages: readonly ChatMessage[], now: Date = new Date(), labels: DayLabels = PL_DAYS): ChatListItem[] { + const out: ChatListItem[] = [] + let prev: ChatMessage | null = null + let prevDay = '' + for (const m of messages) { + const day = dayKey(m.created_at) + const newDay = day !== prevDay + if (newDay) out.push({ kind: 'day', key: `day-${day}`, label: dayLabel(m.created_at, now, labels) }) + const followUp = + !newDay && + prev !== null && + prev.sender_id === m.sender_id && + Date.parse(m.created_at) - Date.parse(prev.created_at) <= GROUP_WINDOW_MS + out.push({ kind: 'message', key: `m-${m.id}`, message: m, followUp }) + prev = m + prevDay = day + } + return out +} + +/** Lowercase without diacritics; ł folds to l (it has no NFD decomposition). */ +export function foldText(s: string): string { + return s + .toLocaleLowerCase('pl-PL') + .replace(/ł/g, 'l') + .normalize('NFD') + .replace(/\p{Diacritic}/gu, '') +} + +/** + * Members other than you whose name, surname or full name starts with the + * query, case- and diacritic-insensitively, sorted by full name. + */ +export function filterMembers(members: Iterable, query: string, meId: number | null): ChatMember[] { + const q = foldText(query.trim()) + const out: ChatMember[] = [] + for (const m of members) { + if (m.id === meId) continue + const name = foldText(m.name ?? '') + const surname = foldText(m.surname ?? '') + if (!q || name.startsWith(q) || surname.startsWith(q) || `${name} ${surname}`.startsWith(q)) out.push(m) + } + return out.sort((a, b) => fullName(a).localeCompare(fullName(b), formatLocale())) +} + +/** At most this many reactor names in a reaction chip's title. */ +export const REACTORS_SHOWN = 10 + +/** "Ola K., Jan N. i 3 innych": who reacted, for a chip's title. more() words the rest. */ +export function reactorsTitle( + userIds: readonly number[], + members: ReadonlyMap, + more: (names: string, rest: number) => string = (names, rest) => `${names} i ${rest} innych`, + unknown?: string, +): string { + const names = userIds.slice(0, REACTORS_SHOWN).map((id) => shortName(members.get(id), '', unknown)) + const rest = userIds.length - names.length + return rest > 0 ? more(names.join(', '), rest) : names.join(', ') +} diff --git a/app/lib/chatText.ts b/app/lib/chatText.ts new file mode 100644 index 0000000..23052ff --- /dev/null +++ b/app/lib/chatText.ts @@ -0,0 +1,143 @@ +/** + * Chat message text (D-12, D-13): an inline-only renderer and the mention + * helpers of the composer. + * + * Safe by construction, like markdown.ts: every character of the message is + * HTML-escaped, and the only tags produced are code, strong, em, br, links + * (through safeUrl) and mention spans. Headings, lists, quotes, images and + * raw HTML never come out. The result is the only thing ever bound with + * v-html in the chat. + */ +import type { ChatMember } from './types' +import { shortName } from './chatFormat' +import { escapeHtml, formatSpans, safeUrl } from './markdown' + +const EXTERNAL = ' target="_blank" rel="noopener noreferrer nofollow"' + +/** + * @handle as golem15.chatchannels extracts it (mention_parser.go): not after + * a word character, a dot or another @, 2 to 255 of [A-Za-z0-9_.-]. + */ +const MENTION_RE = /(?"'`]+/gi + +/** + * A handle as written, or that handle without a trailing dot or dash when + * only that one is known ("dzięki @ola_k." ends a sentence). + */ +function resolveHandle(raw: string, known: (h: string) => boolean): { handle: string; rest: string } | null { + if (known(raw)) return { handle: raw, rest: '' } + const trimmed = raw.replace(/[.-]+$/, '') + if (trimmed.length >= 2 && trimmed !== raw && known(trimmed)) return { handle: trimmed, rest: raw.slice(trimmed.length) } + return null +} + +/** Trailing punctuation after a bare URL stays text; a ")" stays only when the URL opened one. */ +function splitUrl(raw: string): { url: string; rest: string } { + let url = raw + for (;;) { + const last = url.at(-1) + if (!last) break + if ('.,;:!?\'"]}'.includes(last)) { + url = url.slice(0, -1) + continue + } + if (last === ')' && (url.match(/\(/g)?.length ?? 0) < (url.match(/\)/g)?.length ?? 0)) { + url = url.slice(0, -1) + continue + } + break + } + return { url, rest: raw.slice(url.length) } +} + +/** + * The HTML of a message body: code spans, [label](url), bare http(s) URLs, + * mentions of chat members (by handle), bold, italic and line breaks. + * External links open in a new tab without an opener or referrer. + */ +export function renderChatText(src: string | null | undefined, members: ReadonlyMap = new Map()): string { + if (!src) return '' + const stash: string[] = [] + // A held fragment may contain earlier placeholders (a code span inside a + // link label): they are expanded as it is stored, so the final single + // pass never leaves one behind. + const expand = (html: string) => html.replace(/\u0000(\d+)\u0000/g, (_, i: string) => stash[Number(i)] ?? '') + const hold = (html: string) => `\u0000${stash.push(expand(html)) - 1}\u0000` + // eslint-disable-next-line no-control-regex + let s = src.replace(/\r\n?/g, '\n').replace(/\u0000/g, '') + + // Code spans first: their content stays literal. + s = s.replace(CODE_RE, (_, code: string) => hold(`${escapeHtml(code)}`)) + + // Links, before escaping so the URL is seen as written; an unsafe target leaves the label as text. + // A URL holding a code span is not a link at all: the text stays as written. + s = s.replace(LINK_RE, (whole: string, label: string, url: string) => { + if (url.includes('\u0000')) return whole + const safe = safeUrl(url) + const text = formatSpans(escapeHtml(label)) + if (!safe) return hold(text) + const attrs = /^https?:/i.test(safe) ? EXTERNAL : '' + return hold(`${text}`) + }) + + // Bare URLs. + s = s.replace(URL_RE, (raw: string) => { + if (raw.includes('\u0000')) return raw + const { url, rest } = splitUrl(raw) + const safe = safeUrl(url) + if (!safe) return raw + return hold(`${escapeHtml(url)}`) + rest + }) + + // Mentions of chat members; the name shown comes from the member list, never from the text. + s = s.replace(MENTION_RE, (whole: string, raw: string) => { + const hit = resolveHandle(raw, (h) => members.has(h)) + if (!hit) return whole + const m = members.get(hit.handle) + const name = `@${shortName(m)}` + return hold(`${escapeHtml(name)}`) + hit.rest + }) + + s = formatSpans(escapeHtml(s)).replace(/\n/g, '
') + return expand(s) +} + +/** The message mentions this handle (outside code spans), as the server would count it. */ +export function mentionsHandle(src: string | null | undefined, handle: string | null | undefined): boolean { + if (!src || !handle) return false + const text = src.replace(CODE_RE, ' ') + for (const m of text.matchAll(MENTION_RE)) { + if (resolveHandle(m[1], (h) => h === handle)) return true + } + return false +} + +/** An @ query being typed: where the @ is and what follows it up to the caret. */ +export interface MentionQuery { + start: number + query: string +} + +/** + * The mention being typed at the caret: an @ at the start of the text or + * after whitespace, followed by no whitespace up to the caret. null otherwise + * ("mail@x" is not a mention). + */ +export function mentionQuery(text: string, caret: number): MentionQuery | null { + const before = text.slice(0, Math.max(0, caret)) + const m = /(^|\s)@([^\s@]*)$/u.exec(before) + if (!m) return null + return { start: before.length - m[2].length - 1, query: m[2] } +} + +/** Replaces text[start, end) with "@handle " and gives the caret after the space. */ +export function insertMention(text: string, range: { start: number; end: number }, handle: string): { text: string; caret: number } { + const head = text.slice(0, range.start) + const tail = text.slice(range.end) + const token = `@${handle}` + if (tail.startsWith(' ')) return { text: head + token + tail, caret: head.length + token.length + 1 } + return { text: `${head}${token} ${tail}`, caret: head.length + token.length + 1 } +} diff --git a/app/lib/chatUnread.ts b/app/lib/chatUnread.ts new file mode 100644 index 0000000..6037228 --- /dev/null +++ b/app/lib/chatUnread.ts @@ -0,0 +1,64 @@ +// Unread rules for the chat badges, ported from a Golem15 SPA's +// chatUnread.ts. The Polish copy helpers are kept for the SPA's tests; the +// layer's components word the badges through i18n (chat.unread.*). +import type { ChatMessage } from './types' +import { count, plural } from './format' + +export interface ReadInputs { + /** The conversation is the active one. */ + active: boolean + /** The panel is on screen: the desktop column, or the Czat tab selected. */ + visible: boolean + /** document.hasFocus(). */ + focused: boolean + /** The list is within 48px of its bottom. */ + atBottom: boolean +} + +/** shouldMarkRead is D-18: a conversation is read only when it is really seen. */ +export function shouldMarkRead({ active, visible, focused, atBottom }: ReadInputs): boolean { + return active && visible && focused && atBottom +} + +/** badgeText is the visible count: none for 0, capped above 99. */ +export function badgeText(n: number): string { + if (!(n > 0)) return '' + return n > 99 ? '99+' : String(n) +} + +/** unreadLabel is the sr-only text of an unread badge. */ +export function unreadLabel(n: number): string { + return count(n, 'nieprzeczytana wiadomość', 'nieprzeczytane wiadomości', 'nieprzeczytanych wiadomości') +} + +/** mentionLabel is the sr-only text of the @ badge. */ +export function mentionLabel(n: number): string { + if (n === 1) return 'wzmianka o Tobie' + return `${n} ${plural(n, 'wzmianka', 'wzmianki', 'wzmianek')} o Tobie` +} + +/** + * dividerMessageId places "Nowe wiadomości" before the first unread message: + * the first of the last `unread` messages from someone else. With fewer + * loaded than that, the oldest loaded one from someone else. + */ +export function dividerMessageId(messages: readonly ChatMessage[], unread: number, meId: number | null): number | null { + if (!(unread > 0)) return null + let left = unread + let found: number | null = null + for (let i = messages.length - 1; i >= 0 && left > 0; i--) { + const m = messages[i] + if (m.sender_id === meId) continue + found = m.id + left-- + } + return found +} + +/** typingText is the typing row (D-15): zero, one, two, or many people. */ +export function typingText(names: readonly string[]): string { + if (names.length === 0) return '' + if (names.length === 1) return `${names[0]} pisze…` + if (names.length === 2) return `${names[0]} i ${names[1]} piszą…` + return 'Kilka osób pisze…' +} diff --git a/app/lib/client.ts b/app/lib/client.ts index 0a73350..ea4eb5e 100644 --- a/app/lib/client.ts +++ b/app/lib/client.ts @@ -1,5 +1,5 @@ // The chat layer's HTTP client: golem15.chat (/_chat/api/v1), the host -// bootstrap ({hostApiBase}/chat), and later chatchannels and chatbots. Pure +// bootstrap ({hostApiBase}/chat) and golem15.chatchannels. Pure // and Nuxt-free, so tests drive it with a stub fetch; useChatApi binds it to // runtime config and the app's $chatAuth hook. // @@ -23,6 +23,8 @@ export interface ChatAuth { refresh?(): Promise /** Called once a request failed with 401 and the refresh did not help. */ unauthorized?(): void + /** The caller's user id; without it the chat reads the token's numeric sub claim. */ + userId?(): number | null | undefined } /** The API bases: same-origin paths in the browser. */ @@ -74,6 +76,25 @@ export interface MessagePage { before?: number } +/** + * userIdFromToken reads the numeric sub claim of a JWT without verifying it + * (the server does): the chat needs the caller's id for its user:{id} + * channel and to tell its own messages apart. null for anything else. + */ +export function userIdFromToken(token: string | null | undefined): number | null { + if (!token) return null + const part = token.split('.')[1] + if (!part) return null + try { + const b64 = part.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(part.length / 4) * 4, '=') + const claims = JSON.parse(globalThis.atob(b64)) as { sub?: unknown } + const n = typeof claims.sub === 'string' ? Number(claims.sub.trim()) : claims.sub + return typeof n === 'number' && Number.isInteger(n) && n > 0 ? n : null + } catch { + return null + } +} + function joinUrl(base: string, path: string): string { return `${base.replace(/\/+$/, '')}${path}` } @@ -200,6 +221,8 @@ export function createChatClient(opts: ChatClientOptions) { } const chat = (path: string) => joinUrl(bases.chat, path) + const channels = (context: { type: string; id: number }, path: string) => + joinUrl(bases.channels, `/contexts/${encodeURIComponent(context.type)}/${context.id}${path}`) const host = (path: string) => { if (!bases.host) throw new ChatApiError(0, 'public.chat.hostApiBase is not set') return joinUrl(bases.host, path) @@ -220,6 +243,21 @@ export function createChatClient(opts: ChatClientOptions) { /** 201 with the message itself. */ send: (conversationId: number, body: ChatSendBody) => request(chat(`/conversations/${conversationId}/messages`), { method: 'POST', body }), + /** One message (content for a created event, which carries ids only). */ + message: (id: number) => request(chat(`/messages/${id}`)), + /** Marks a conversation read up to now; golem15.chat tells the other participants. */ + markRead: (conversationId: number) => request(chat(`/conversations/${conversationId}/read`), { method: 'POST' }), + /** Emits typing.chat.message on the conversation channel. */ + typing: (conversationId: number) => request(chat(`/conversations/${conversationId}/typing`), { method: 'POST' }), + /** Finds or creates the DM with a member of the context (chat-dm bucket, 10/min). */ + startDm: (context: { type: string; id: number }, userId: number) => + request(chat(`/contexts/${encodeURIComponent(context.type)}/${context.id}/dm`), { method: 'POST', body: { user_id: userId } }), + /** Joins a public channel of the context (golem15.chatchannels). */ + joinChannel: (context: { type: string; id: number }, channelId: number) => + request(channels(context, `/channels/${channelId}/join`), { method: 'POST' }), + /** Leaves a channel; it stays listed with joined false. */ + leaveChannel: (context: { type: string; id: number }, channelId: number) => + request(channels(context, `/channels/${channelId}/leave`), { method: 'POST' }), } } diff --git a/app/lib/format.ts b/app/lib/format.ts new file mode 100644 index 0000000..701cdae --- /dev/null +++ b/app/lib/format.ts @@ -0,0 +1,89 @@ +// Dates, plurals and sizes for the chat, ported from a Golem15 SPA's +// format.ts (only the helpers the chat uses). The SPA formatted for pl-PL in +// Europe/Warsaw; here the locale and the time zone are module settings with +// those defaults, and the layer's components set them from the app's locale +// and the browser's time zone (setFormatLocale). + +let LOCALE = 'pl-PL' +let TZ: string | undefined = 'Europe/Warsaw' + +interface Formatters { + time: Intl.DateTimeFormat + dayLong: Intl.DateTimeFormat + date: Intl.DateTimeFormat + dateShort: Intl.DateTimeFormat + key: Intl.DateTimeFormat +} + +let f: Formatters | null = null + +function formatters(): Formatters { + if (f) return f + const dtf = (opts: Intl.DateTimeFormatOptions) => new Intl.DateTimeFormat(LOCALE, { timeZone: TZ, ...opts }) + f = { + time: dtf({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }), + dayLong: dtf({ weekday: 'long', day: 'numeric', month: 'long' }), + date: dtf({ day: 'numeric', month: 'long', year: 'numeric' }), + dateShort: dtf({ day: 'numeric', month: 'short' }), + key: new Intl.DateTimeFormat('sv-SE', { timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit' }), + } + return f +} + +/** + * setFormatLocale sets the locale (a BCP 47 tag such as en-US) and, + * optionally, the IANA time zone of every chat date; an empty time zone + * means the runtime's own. + */ +export function setFormatLocale(locale: string, timeZone?: string) { + const zone = timeZone === undefined ? TZ : timeZone || undefined + if (locale === LOCALE && zone === TZ) return + LOCALE = locale || LOCALE + TZ = zone + f = null +} + +/** The current format locale. */ +export function formatLocale(): string { + return LOCALE +} + +/** Polish plural: 1 plik, 2 pliki, 5 plików, 12 plików, 22 pliki. */ +export function plural(n: number, one: string, few: string, many: string): string { + const abs = Math.abs(n) + if (abs === 1) return one + const last = abs % 10 + const last2 = abs % 100 + if (last >= 2 && last <= 4 && !(last2 >= 12 && last2 <= 14)) return few + return many +} + +/** "5 pytań", "1 pytanie". */ +export function count(n: number, one: string, few: string, many: string): string { + return `${n} ${plural(n, one, few, many)}` +} + +export const fmtTime = (iso: string) => formatters().time.format(new Date(iso)) +export const fmtDay = (iso: string) => formatters().dayLong.format(new Date(iso)) +export const fmtDate = (iso: string) => formatters().date.format(new Date(iso)) +export const fmtDateShort = (iso: string) => formatters().dateShort.format(new Date(iso)) +export const fmtDateTime = (iso: string) => `${fmtDate(iso)}, ${fmtTime(iso)}` + +/** The calendar day of an instant in the format time zone, `YYYY-MM-DD`. */ +export const dayKey = (iso: string | Date) => formatters().key.format(typeof iso === 'string' ? new Date(iso) : iso) +export const todayKey = (now: Date = new Date()) => dayKey(now) + +/** Whole calendar days from `now` to `iso` (negative when past). */ +export function daysUntil(iso: string, now: Date = new Date()): number { + const a = Date.parse(`${todayKey(now)}T00:00:00Z`) + const b = Date.parse(`${dayKey(iso)}T00:00:00Z`) + return Math.round((b - a) / 86_400_000) +} + +/** A byte count: "512 B", "12 KB", "1,5 MB" (the decimal mark of the locale). */ +export function fmtSize(bytes: number): string { + if (bytes < 1024) return `${bytes} B` + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB` + const mb = (bytes / 1024 / 1024).toFixed(1) + return `${LOCALE.startsWith('en') ? mb : mb.replace('.', ',')} MB` +} diff --git a/app/lib/markdown.ts b/app/lib/markdown.ts new file mode 100644 index 0000000..4eb7276 --- /dev/null +++ b/app/lib/markdown.ts @@ -0,0 +1,32 @@ +// HTML helpers of the chat text renderer (chatText.ts), ported from a +// Golem15 SPA's markdown.ts: escaping, the link-target allow-list and +// bold/italic on escaped text. +// +// Links must be http(s), mailto, a site path or an anchor; anything else +// (javascript:, data:, ...) is refused. + +const ESC: Record = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' } + +export function escapeHtml(s: string): string { + return s.replace(/[&<>"']/g, (c) => ESC[c]) +} + +/** Returns the URL when it is allowed as a link target, else null. */ +export function safeUrl(raw: string): string | null { + // Strip whitespace and control characters browsers ignore inside schemes. + // eslint-disable-next-line no-control-regex + const url = raw.trim().replace(/[\u0000-\u001f\u007f\s]+/g, '') + if (/^https?:\/\/[^/]/i.test(url) || /^mailto:[^\s]+$/i.test(url)) return url + // A site path: a "/" not followed by another "/" or a backslash (browsers + // read "/\host" as "//host", an external link). + if (/^\/(?![/\\])/.test(url) || url.startsWith('#')) return url + return null +} + +/** Bold and italic on already-escaped text (shared with the chat renderer). */ +export function formatSpans(escaped: string): string { + return escaped + .replace(/\*\*([^*\n]+)\*\*/g, '$1') + .replace(/(^|[\s(])\*([^*\n]+)\*(?=$|[\s).,;:!?])/g, '$1$2') + .replace(/(^|[\s(])_([^_\n]+)_(?=$|[\s).,;:!?])/g, '$1$2') +} diff --git a/app/lib/media.ts b/app/lib/media.ts new file mode 100644 index 0000000..9ad39b9 --- /dev/null +++ b/app/lib/media.ts @@ -0,0 +1,20 @@ +import { getCurrentScope, onScopeDispose, ref, type Ref } from 'vue' + +/** A reactive matchMedia; false where matchMedia does not exist (tests, SSR). */ +export function useMediaQuery(query: string): Ref { + const matches = ref(false) + if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return matches + const mql = window.matchMedia(query) + matches.value = mql.matches + const update = (e: MediaQueryListEvent) => { + matches.value = e.matches + } + mql.addEventListener('change', update) + if (getCurrentScope()) onScopeDispose(() => mql.removeEventListener('change', update)) + return matches +} + +/** True at and above a viewport width (the CSS `min-width` breakpoints). */ +export function useMinWidth(px: number): Ref { + return useMediaQuery(`(min-width: ${px}px)`) +} diff --git a/app/lib/realtime.ts b/app/lib/realtime.ts new file mode 100644 index 0000000..3c30a04 --- /dev/null +++ b/app/lib/realtime.ts @@ -0,0 +1,417 @@ +// The page's one Centrifuge client, ported from a Golem15 SPA's +// lib/realtime.ts. Chat, its satellite layers and any other page code +// (a presentations speaker view and phone remote, for example) subscribe +// through it, so a page never holds a second socket. +// +// Nuxt-free: the app (or the chat store, from $chatAuth) hands it the +// user's token through setRealtimeAuth. The connection token comes from +// GET /api/realtime/token with that bearer; one 401 renews the user's token +// through the refresh callback and retries. +import type { Centrifuge, Subscription } from 'centrifuge' + +/** REALTIME_WS_PATH matches realtime.centrifugo.ws_url and the nginx `location = /ws` block. */ +export const REALTIME_WS_PATH = '/ws' + +/** TOKEN_PATH is the lighthouse connection-token route; the host decides who gets a token. */ +export const TOKEN_PATH = '/api/realtime/token' + +/** + * Token answers that mean "realtime is not for this session"; the client + * stops retrying. 503 is not one of them: the access guard answers 503 for a + * database hiccup too, and a token refresh (about hourly) that hit one would + * otherwise end the remote for the rest of the talk. A 503 is rethrown as an + * ordinary error, so the client retries with backoff. + */ +const UNAVAILABLE = new Set([401, 403, 404]) + +/** tokenFailureIsFinal reports whether a token-route status stops the client for good. */ +export function tokenFailureIsFinal(status: number): boolean { + return UNAVAILABLE.has(status) +} + +export type ConnectionState = 'connecting' | 'connected' | 'disconnected' + +export interface ChannelHooks { + onPublication(data: unknown): void + onSubscribed?(): void + onConnection?(state: ConnectionState): void + onDenied?(code: number): void + onUnavailable?(): void +} + +export interface ChannelHandle { + close(): void + resubscribe(): void +} + +/** A token-route refusal: the HTTP status, 0 without a connection. */ +export class RealtimeTokenError extends Error { + status: number + constructor(status: number, message: string) { + super(message) + this.name = 'RealtimeTokenError' + this.status = status + } +} + +type TokenGetter = () => string | null | undefined +type TokenRefresher = () => Promise + +let authToken: TokenGetter | null = null +let authRefresh: TokenRefresher | null = null + +/** + * setRealtimeAuth gives the client the user's token getter (the frontend + * JWT sent as the bearer of the token route) and, optionally, its renewal. + * The latest call wins. + */ +export function setRealtimeAuth(getToken: TokenGetter, refresh?: TokenRefresher) { + authToken = getToken + authRefresh = refresh ?? null +} + +/** hasRealtimeAuth reports whether setRealtimeAuth ran. */ +export function hasRealtimeAuth(): boolean { + return authToken !== null +} + +function bearer(): string | null { + try { + return authToken?.() || null + } catch { + return null + } +} + +async function tokenRequest(user: string | null): Promise { + const headers: Record = { Accept: 'application/json' } + if (user) headers.Authorization = `Bearer ${user}` + try { + return await fetch(TOKEN_PATH, { method: 'GET', headers }) + } catch { + throw new RealtimeTokenError(0, 'realtime: no connection') + } +} + +/** + * fetchConnectionToken asks the token route for a Centrifugo connection + * token. A 401 with a user token renews it once through the refresh + * callback and retries. Refusals throw RealtimeTokenError with the status. + */ +export async function fetchConnectionToken(): Promise { + const used = bearer() + let res = await tokenRequest(used) + if (res.status === 401 && used && authRefresh) { + let next: string | null = null + try { + next = (await authRefresh()) || null + } catch { + next = null + } + if (next) res = await tokenRequest(next) + } + if (!res.ok) throw new RealtimeTokenError(res.status, `realtime: token route answered ${res.status}`) + let got: unknown = null + try { + got = await res.json() + } catch { + got = null + } + const body = (got && typeof got === 'object' && 'data' in got ? (got as { data: unknown }).data : got) as { token?: unknown } | null + if (!body || typeof body.token !== 'string' || body.token === '') throw new Error('realtime: empty token') + return body.token +} + +type UserEventHandler = (data: unknown) => void +const userEventHandlers = new Set() + +/** + * onUserEvent hears the publications on the user's own channel (user:{me}) + * that the chat does not handle itself (for example video:* events of a + * call layer). The chat holds the one user:{me} subscription; a second + * layer must not subscribe to it. Returns the unlisten function. + */ +export function onUserEvent(handler: UserEventHandler): () => void { + userEventHandlers.add(handler) + return () => void userEventHandlers.delete(handler) +} + +/** dispatchUserEvent hands one user:{me} publication to every onUserEvent handler. */ +export function dispatchUserEvent(data: unknown) { + for (const h of [...userEventHandlers]) { + try { + h(data) + } catch (err) { + console.error('vue-chat-layer: a user event handler failed', err) + } + } +} + +/** One subscribed connection in a channel's presence; user is the token subject. */ +export interface PresenceClient { + client: string + user: number +} + +/** Hooks of one subscribe() handle; every handle on a channel hears every event. */ +export interface SubscribeHooks { + onPublication?(data: unknown): void + onSubscribed?(): void + onDenied?(code: number): void + onJoin?(who: PresenceClient): void + onLeave?(who: PresenceClient): void +} + +/** wsURL is the WebSocket endpoint on the page's own host. */ +export function wsURL(loc: Pick = window.location): string { + return `${loc.protocol === 'https:' ? 'wss' : 'ws'}://${loc.host}${REALTIME_WS_PATH}` +} + +function connectionState(value: unknown): ConnectionState { + const s = String(value) + if (s === 'connected' || s === 'connecting') return s + return 'disconnected' +} + +function presenceClient(info: { client?: unknown; user?: unknown } | null | undefined): PresenceClient | null { + if (!info || typeof info.client !== 'string') return null + const user = Number(info.user) + if (!Number.isInteger(user) || user <= 0) return null + return { client: info.client, user } +} + +interface Entry { + sub: Subscription + hooks: Set +} + +// The page's one client. Chat, the speaker view and the phone remote all +// subscribe through it, so the app never holds a second socket. +let centrifuge: Centrifuge | null = null +let connecting: Promise | null = null +let state: ConnectionState = 'disconnected' +let unavailable = false +/** Bumped by disconnect(): a client still loading for an older session is dropped. */ +let epoch = 0 +const entries = new Map() +const connectionListeners = new Set<(s: ConnectionState) => void>() +const unavailableListeners = new Set<() => void>() + +function setState(next: ConnectionState) { + state = next + for (const l of [...connectionListeners]) l(next) +} + +function markUnavailable() { + unavailable = true + for (const l of [...unavailableListeners]) l() +} + +/** realtimeState is the shared client's connection state. */ +export function realtimeState(): ConnectionState { + return state +} + +/** realtimeUnavailable reports a final token refusal for this session. */ +export function realtimeUnavailable(): boolean { + return unavailable +} + +/** onConnection listens to the shared client's state; returns the unlisten function. */ +export function onConnection(listener: (s: ConnectionState) => void): () => void { + connectionListeners.add(listener) + return () => void connectionListeners.delete(listener) +} + +/** + * onUnavailable listens for a final token refusal (401, 403, 404). A listener + * added after the refusal hears it at once, on a microtask. + */ +export function onUnavailable(listener: () => void): () => void { + unavailableListeners.add(listener) + if (unavailable) queueMicrotask(() => unavailableListeners.has(listener) && listener()) + return () => void unavailableListeners.delete(listener) +} + +/** + * connect returns the shared client, creating it on first use. The client + * package is loaded here, on demand, so no page that never subscribes pulls + * it in. The connection token is fetched (and refreshed) from the token + * route, never passed in statically. + */ +export function connect(): Promise { + if (centrifuge) { + if (state === 'disconnected' && !unavailable) centrifuge.connect() + return Promise.resolve(centrifuge) + } + if (connecting) return connecting + const mine = epoch + connecting = (async () => { + try { + const { Centrifuge, UnauthorizedError } = await import('centrifuge') + if (mine !== epoch) throw new Error('realtime: disconnected while loading') + const c = new Centrifuge(wsURL(), { + minReconnectDelay: 500, + maxReconnectDelay: 10000, + getToken: async () => { + try { + return await fetchConnectionToken() + } catch (err) { + if (err instanceof RealtimeTokenError && tokenFailureIsFinal(err.status)) { + markUnavailable() + throw new UnauthorizedError('realtime unavailable') + } + throw err + } + }, + }) + c.on('state', (ctx) => { + if (centrifuge === c) setState(connectionState(ctx.newState)) + }) + centrifuge = c + c.connect() + return c + } finally { + if (mine === epoch) connecting = null + } + })() + return connecting +} + +function each(entry: Entry, call: (h: SubscribeHooks) => void) { + for (const h of [...entry.hooks]) call(h) +} + +function attach(c: Centrifuge, channel: string, hooks: SubscribeHooks): Entry { + let entry = entries.get(channel) + if (!entry) { + const sub = c.getSubscription(channel) ?? c.newSubscription(channel) + const e: Entry = { sub, hooks: new Set() } + sub.on('publication', (ctx) => each(e, (h) => h.onPublication?.(ctx.data))) + sub.on('subscribed', () => each(e, (h) => h.onSubscribed?.())) + sub.on('unsubscribed', (ctx) => { + if (ctx.code >= 400) each(e, (h) => h.onDenied?.(ctx.code)) + }) + sub.on('join', (ctx) => { + const who = presenceClient(ctx.info) + if (who) each(e, (h) => h.onJoin?.(who)) + }) + sub.on('leave', (ctx) => { + const who = presenceClient(ctx.info) + if (who) each(e, (h) => h.onLeave?.(who)) + }) + entries.set(channel, e) + sub.subscribe() + entry = e + } else if (String(entry.sub.state) === 'subscribed') { + // A later handle on a live channel still gets its "subscribed" (gap fill, presence). + queueMicrotask(() => entry?.hooks.has(hooks) && hooks.onSubscribed?.()) + } + entry.hooks.add(hooks) + return entry +} + +function detach(channel: string, entry: Entry) { + entry.sub.removeAllListeners() + entry.sub.unsubscribe() + centrifuge?.removeSubscription(entry.sub) + entries.delete(channel) +} + +/** + * subscribe joins a channel on the shared client. Handles on the same channel + * share one Subscription; the channel is left when its last handle closes, + * and the socket disconnects when no channel is left. + */ +export async function subscribe(channel: string, hooks: SubscribeHooks): Promise { + const c = await connect() + const own: SubscribeHooks = { ...hooks } + const mine = epoch + attach(c, channel, own) + let closed = false + return { + close() { + if (closed) return + closed = true + const entry = entries.get(channel) + if (mine !== epoch || !entry || !entry.hooks.delete(own)) return + if (entry.hooks.size > 0) return + detach(channel, entry) + if (entries.size === 0 && centrifuge === c) c.disconnect() + }, + resubscribe() { + if (closed || mine !== epoch) return + entries.get(channel)?.sub.subscribe() + }, + } +} + +/** presence lists the clients subscribed to a channel this page has joined; null when unavailable. */ +export async function presence(channel: string): Promise { + const entry = entries.get(channel) + if (!entry) return null + try { + const got = await entry.sub.presence() + return Object.values(got.clients ?? {}) + .map((info) => presenceClient(info)) + .filter((p): p is PresenceClient => p !== null) + } catch { + return null + } +} + +/** + * disconnect closes every channel and the socket and forgets the client (on + * logout): the next session gets a fresh client and a fresh token. + */ +export function disconnect() { + epoch++ + connecting = null + for (const [channel, entry] of [...entries]) detach(channel, entry) + const c = centrifuge + centrifuge = null + unavailable = false + if (c) { + c.disconnect() + c.removeAllListeners() + } + if (state !== 'disconnected') setState('disconnected') +} + +/** + * openChannel subscribes one channel for the presentations speaker view and + * phone remote, over the shared client. Its hooks also hear the client's + * connection state (at once when the socket is already up) and a final + * token refusal. + */ +export async function openChannel(channel: string, hooks: ChannelHooks): Promise { + const offConnection = onConnection((s) => hooks.onConnection?.(s)) + const offUnavailable = onUnavailable(() => hooks.onUnavailable?.()) + let handle: ChannelHandle + try { + handle = await subscribe(channel, { + onPublication: (data) => hooks.onPublication(data), + onSubscribed: () => hooks.onSubscribed?.(), + onDenied: (code) => hooks.onDenied?.(code), + }) + } catch (err) { + offConnection() + offUnavailable() + throw err + } + // A socket that was already up for another channel sends no new 'connected'. + if (state === 'connected') hooks.onConnection?.(state) + let closed = false + return { + close() { + if (closed) return + closed = true + offConnection() + offUnavailable() + handle.close() + }, + resubscribe() { + if (!closed) handle.resubscribe() + }, + } +} diff --git a/app/lib/tabs.ts b/app/lib/tabs.ts new file mode 100644 index 0000000..2f88f4a --- /dev/null +++ b/app/lib/tabs.ts @@ -0,0 +1,19 @@ +/** + * The tab a key moves to in a tablist with automatic activation: Left and + * Right wrap, Home and End jump. null for any other key. + */ +export function nextIndex(key: string, index: number, count: number): number | null { + if (count <= 0) return null + switch (key) { + case 'ArrowRight': + return (index + 1) % count + case 'ArrowLeft': + return (index - 1 + count) % count + case 'Home': + return 0 + case 'End': + return count - 1 + default: + return null + } +} diff --git a/i18n/locales/en.json b/i18n/locales/en.json index aa122fa..361e3f9 100644 --- a/i18n/locales/en.json +++ b/i18n/locales/en.json @@ -2,13 +2,96 @@ "chat": { "name": "Chat", "channels": "Channels", - "messages": "Messages", - "message": "Message", + "channelsLeft": "Channels you left", + "join": "Join", "send": "Send", - "pickChannel": "Pick a channel to start.", + "retry": "Try again", + "close": "Close", + "loading": "Loading", + "someone": "Someone", + "notMember": "Your account is not a member of this chat.", + "pickTitle": "Pick a conversation", + "pickText": "Open a channel or a direct message on the left, or start a new message.", "error": { "bootstrap": "The chat could not load. Check your connection and try again.", - "send": "The message was not sent. Try again." + "load": "The messages could not load. Check your connection and try again.", + "older": "Older messages could not load.", + "send": "The message was not sent. Try again.", + "offline": "Not sent: no internet connection. Try again.", + "tooFast": "Too many messages in a short time. Wait a moment and send again.", + "noAccess": "You no longer have access to this conversation.", + "refused": "This message cannot be sent. Check its text and attachments.", + "dm": "The conversation could not start. Try again.", + "tooManyDms": "Too many new conversations in a short time. Wait a minute and try again.", + "openChannel": "The channel could not open. Try again.", + "leaveChannel": "You could not leave the channel. Try again.", + "joinChannel": "You could not join the channel. Try again." + }, + "unread": { + "messages": "{n} unread message | {n} unread messages", + "mentions": "{n} mention of you | {n} mentions of you" + }, + "dm": { + "title": "Direct messages", + "new": "New message", + "you": "You: {text}", + "failed": "Your conversations could not load.", + "empty": "No direct messages yet. Start one with the + button." + }, + "picker": { + "to": "To", + "placeholder": "Type a name", + "failed": "The member list could not load.", + "nobody": "There is nobody else in the chat yet.", + "noMatch": "Nobody matches “{q}”." + }, + "mention": { + "label": "Mention someone", + "none": "Nobody matches “{q}”." + }, + "msg": { + "bot": "Bot", + "you": "You", + "edited": "(edited)", + "editedAt": "Edited {at}", + "deleted": "Message deleted." + }, + "day": { + "today": "Today", + "yesterday": "Yesterday" + }, + "list": { + "label": "Messages in {name}", + "startDm": "This is the start of your conversation with {name}.", + "startChannel": "This is the start of {name}.", + "olderLoading": "Loading older messages…", + "new": "New messages", + "jump": "New messages: {n}" + }, + "composer": { + "mention": "Mention someone", + "hint": "Enter sends, Shift+Enter adds a new line.", + "label": "Message to {name}", + "placeholder": "Message {name}" + }, + "header": { + "channel": "Channel", + "dm": "Direct message", + "back": "Back to the conversations", + "online": "{n} online", + "onlyYou": "only you", + "dmOnline": "online", + "leave": "Leave the channel" + }, + "connection": { + "connecting": "Connecting to the chat…", + "reconnecting": "Reconnecting…", + "unavailable": "No live updates: the chat refreshes every 15 seconds." + }, + "typing": { + "one": "{a} is typing…", + "two": "{a} and {b} are typing…", + "many": "Several people are typing…" } } } diff --git a/i18n/locales/pl.json b/i18n/locales/pl.json index 08cf105..983f14e 100644 --- a/i18n/locales/pl.json +++ b/i18n/locales/pl.json @@ -2,13 +2,96 @@ "chat": { "name": "Czat", "channels": "Kanały", - "messages": "Wiadomości", - "message": "Wiadomość", + "channelsLeft": "Kanały, które opuszczono", + "join": "Dołącz", "send": "Wyślij", - "pickChannel": "Wybierz kanał, aby zacząć.", + "retry": "Spróbuj ponownie", + "close": "Zamknij", + "loading": "Wczytywanie", + "someone": "Ktoś", + "notMember": "Twoje konto nie należy do tego czatu.", + "pickTitle": "Wybierz rozmowę", + "pickText": "Otwórz kanał albo wiadomość prywatną po lewej lub zacznij nową wiadomość.", "error": { "bootstrap": "Nie udało się wczytać czatu. Sprawdź połączenie i spróbuj ponownie.", - "send": "Nie wysłano wiadomości. Spróbuj ponownie." + "load": "Nie udało się wczytać wiadomości. Sprawdź połączenie i spróbuj ponownie.", + "older": "Nie udało się wczytać starszych wiadomości.", + "send": "Nie wysłano wiadomości. Spróbuj ponownie.", + "offline": "Nie wysłano: brak połączenia z internetem. Spróbuj ponownie.", + "tooFast": "Za dużo wiadomości w krótkim czasie. Odczekaj chwilę i wyślij ponownie.", + "noAccess": "Nie masz już dostępu do tej rozmowy.", + "refused": "Tej wiadomości nie da się wysłać. Sprawdź treść i załączniki.", + "dm": "Nie udało się rozpocząć rozmowy. Spróbuj ponownie.", + "tooManyDms": "Za dużo nowych rozmów w krótkim czasie. Odczekaj minutę i spróbuj ponownie.", + "openChannel": "Nie udało się otworzyć kanału. Spróbuj ponownie.", + "leaveChannel": "Nie udało się opuścić kanału. Spróbuj ponownie.", + "joinChannel": "Nie udało się dołączyć do kanału. Spróbuj ponownie." + }, + "unread": { + "messages": "nieprzeczytane: {n}", + "mentions": "wzmianki o Tobie: {n}" + }, + "dm": { + "title": "Wiadomości prywatne", + "new": "Nowa wiadomość", + "you": "Ty: {text}", + "failed": "Nie udało się wczytać rozmów.", + "empty": "Nie masz jeszcze wiadomości prywatnych. Zacznij rozmowę przyciskiem +." + }, + "picker": { + "to": "Do kogo?", + "placeholder": "Wpisz imię lub nazwisko", + "failed": "Nie udało się wczytać listy osób.", + "nobody": "Na czacie nie ma jeszcze innych osób.", + "noMatch": "Nikt nie pasuje do „{q}”." + }, + "mention": { + "label": "Wspomnij osobę", + "none": "Brak osób pasujących do „{q}”." + }, + "msg": { + "bot": "Bot", + "you": "Ty", + "edited": "(edytowano)", + "editedAt": "Edytowano {at}", + "deleted": "Wiadomość usunięta." + }, + "day": { + "today": "Dziś", + "yesterday": "Wczoraj" + }, + "list": { + "label": "Wiadomości w {name}", + "startDm": "To początek Waszej rozmowy z {name}.", + "startChannel": "To początek kanału {name}.", + "olderLoading": "Wczytywanie starszych wiadomości…", + "new": "Nowe wiadomości", + "jump": "Nowe wiadomości: {n}" + }, + "composer": { + "mention": "Wspomnij osobę", + "hint": "Enter wysyła, Shift+Enter dodaje nową linię.", + "label": "Wiadomość do {name}", + "placeholder": "Wiadomość do {name}" + }, + "header": { + "channel": "Kanał", + "dm": "Wiadomość prywatna", + "back": "Wróć do rozmów", + "online": "online: {n}", + "onlyYou": "tylko Ty", + "dmOnline": "online", + "leave": "Opuść kanał" + }, + "connection": { + "connecting": "Łączenie z czatem…", + "reconnecting": "Ponowne łączenie…", + "unavailable": "Czat bez aktualizacji na żywo: odświeżam co 15 sekund." + }, + "typing": { + "one": "{a} pisze…", + "two": "{a} i {b} piszą…", + "many": "Kilka osób pisze…" } } }