Files
vue-chat-layer/app/lib/chatFormat.ts
Jakub Zych 5d581539b3 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
2026-10-31 13:52:56 +01:00

139 lines
5.5 KiB
TypeScript

// 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(', ')
}