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
This commit is contained in:
Jakub Zych
2026-10-31 13:52:56 +01:00
parent fa6f9950a6
commit 5d581539b3
27 changed files with 3516 additions and 92 deletions

186
app/lib/chatEvents.ts Normal file
View File

@@ -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<string, unknown> {
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<number, ChatMessage[] | undefined>): 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
}

138
app/lib/chatFormat.ts Normal file
View File

@@ -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<ChatMember, 'name' | 'surname' | 'handle'> & { 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<ChatMember>, 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<number, ChatMember>,
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(', ')
}

143
app/lib/chatText.ts Normal file
View File

@@ -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 = /(?<![A-Za-z0-9_.@])@([A-Za-z0-9_.-]{2,255})/g
const CODE_RE = /`([^`\n]+)`/g
const LINK_RE = /\[([^\]\n]+)\]\(([^()\s]*(?:\([^()\s]*\)[^()\s]*)*)\)/g
const URL_RE = /(?<![\w/@.])https?:\/\/[^\s<>"'`]+/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<string, ChatMember> = 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(`<code>${escapeHtml(code)}</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(`<a href="${escapeHtml(safe)}"${attrs}>${text}</a>`)
})
// 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(`<a href="${escapeHtml(safe)}"${EXTERNAL}>${escapeHtml(url)}</a>`) + 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(`<span class="mention" title="@${escapeHtml(hit.handle)}">${escapeHtml(name)}</span>`) + hit.rest
})
s = formatSpans(escapeHtml(s)).replace(/\n/g, '<br>')
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 }
}

64
app/lib/chatUnread.ts Normal file
View File

@@ -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…'
}

View File

@@ -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<string | null | undefined>
/** 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<ChatMessage>(chat(`/conversations/${conversationId}/messages`), { method: 'POST', body }),
/** One message (content for a created event, which carries ids only). */
message: (id: number) => request<ChatMessage>(chat(`/messages/${id}`)),
/** Marks a conversation read up to now; golem15.chat tells the other participants. */
markRead: (conversationId: number) => request<unknown>(chat(`/conversations/${conversationId}/read`), { method: 'POST' }),
/** Emits typing.chat.message on the conversation channel. */
typing: (conversationId: number) => request<unknown>(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<ChatConversation>(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<unknown>(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<unknown>(channels(context, `/channels/${channelId}/leave`), { method: 'POST' }),
}
}

89
app/lib/format.ts Normal file
View File

@@ -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`
}

32
app/lib/markdown.ts Normal file
View File

@@ -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<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }
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, '<strong>$1</strong>')
.replace(/(^|[\s(])\*([^*\n]+)\*(?=$|[\s).,;:!?])/g, '$1<em>$2</em>')
.replace(/(^|[\s(])_([^_\n]+)_(?=$|[\s).,;:!?])/g, '$1<em>$2</em>')
}

20
app/lib/media.ts Normal file
View File

@@ -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<boolean> {
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<boolean> {
return useMediaQuery(`(min-width: ${px}px)`)
}

417
app/lib/realtime.ts Normal file
View File

@@ -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<string | null | undefined>
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<Response> {
const headers: Record<string, string> = { 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<string> {
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<UserEventHandler>()
/**
* 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<Location, 'protocol' | 'host'> = 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<SubscribeHooks>
}
// 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<Centrifuge> | 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<string, Entry>()
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<Centrifuge> {
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<ChannelHandle> {
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<PresenceClient[] | null> {
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<ChannelHandle> {
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()
},
}
}

19
app/lib/tabs.ts Normal file
View File

@@ -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
}
}