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

View File

@@ -0,0 +1,20 @@
<script setup lang="ts">
// Initials on a palette colour derived from the user id. Never an image:
// sender_avatar from the chat API may point at an external host.
import type { ChatMember } from '../../lib/types'
import { avatarIndex, initials } from '../../lib/chatFormat'
const props = withDefaults(defineProps<{ userId: number; member?: ChatMember | null; fallback?: string; size?: 24 | 32 | 44; me?: boolean }>(), {
member: null,
fallback: '',
size: 32,
me: false,
})
const text = computed(() => initials(props.member, props.fallback))
const fill = computed(() => (props.me ? undefined : { background: `var(--chat-av-${avatarIndex(props.userId)})` }))
</script>
<template>
<span class="chat-avatar" :class="[`chat-avatar--${size}`, { 'chat-avatar--me': me }]" :style="fill" aria-hidden="true">{{ text }}</span>
</template>

View File

@@ -1,25 +1,62 @@
<script setup lang="ts">
// The seeded channels of the community. There is no create button: members
// join and leave the channels the host has.
// The host's channels: the joined ones to open, the ones the user left to
// join again. There is no create button: members join and leave the
// channels the host seeds. The sidebar-footer slot sits below the list
// (an app's link to its friends page, for example).
import type { ChatChannel } from '../../lib/types'
import { badgeText } from '../../lib/chatUnread'
const emit = defineEmits<{ opened: [conversationId: number] }>()
const { t } = useI18n()
const chat = useChat()
const left = computed(() => chat.channels.filter((c) => !c.joined))
const busy = ref<number | null>(null)
async function open(c: ChatChannel) {
if (busy.value !== null) return
busy.value = c.id
try {
if (await chat.openChannel(c)) emit('opened', c.conversation_id)
} finally {
busy.value = null
}
}
</script>
<template>
<nav class="chat-sidebar" :aria-label="t('chat.channels')">
<h2 class="chat-sidebar-title">{{ t('chat.channels') }}</h2>
<ul class="chat-channels">
<li v-for="c in chat.channels.value" :key="c.id">
<nav class="chat-channels" :aria-label="t('chat.channels')">
<h2 class="chat-section-title">{{ t('chat.channels') }}</h2>
<ul class="chat-rows">
<li v-for="c in chat.joinedChannels" :key="c.id">
<button
class="chat-channel"
class="chat-row chat-channel"
:class="{ 'is-unread': c.unread > 0, 'is-active': chat.activeId === c.conversation_id }"
type="button"
:data-channel-slug="c.slug"
:aria-current="chat.activeId.value === c.conversation_id ? 'true' : undefined"
@click="chat.open(c)"
:aria-current="chat.activeId === c.conversation_id ? 'true' : undefined"
:aria-busy="busy === c.id ? 'true' : undefined"
@click="open(c)"
>
# {{ c.name }}
<span class="chat-row-name"><span aria-hidden="true">#</span> {{ c.name }}</span>
<span v-if="c.mentions > 0" class="chat-badge chat-badge--mention"
><span aria-hidden="true">@</span><span class="chat-sr">, {{ t('chat.unread.mentions', { n: c.mentions }, c.mentions) }}</span></span
>
<span v-if="badgeText(c.unread)" class="chat-badge"
><span aria-hidden="true">{{ badgeText(c.unread) }}</span><span class="chat-sr">, {{ t('chat.unread.messages', { n: c.unread }, c.unread) }}</span></span
>
</button>
</li>
</ul>
<template v-if="left.length">
<h3 class="chat-section-subtitle">{{ t('chat.channelsLeft') }}</h3>
<ul class="chat-rows">
<li v-for="c in left" :key="c.id" class="chat-row chat-row--static">
<span class="chat-row-name"><span aria-hidden="true">#</span> {{ c.name }}</span>
<button class="chat-link-btn" type="button" :data-channel-slug="c.slug" :disabled="busy === c.id" @click="open(c)">{{ t('chat.join') }}</button>
</li>
</ul>
</template>
<slot name="sidebar-footer" />
</nav>
</template>

View File

@@ -1,28 +1,237 @@
<script setup lang="ts">
// The message form: Enter sends, Shift+Enter adds a line.
const props = defineProps<{ conversationId: number }>()
// The message form. The draft lives in the chat store, per conversation, so
// it survives switching conversations and routes. Enter sends, Shift+Enter
// adds a line; the field grows to 8 lines, then scrolls.
//
// Mentions: an @ at a word start (or the @ button) opens a WAI-ARIA 1.2
// combobox on the textarea. While its list is open, Enter and Tab pick and
// never send.
import type { ChatMember } from '../../lib/types'
import { filterMembers } from '../../lib/chatFormat'
import { insertMention, mentionQuery, type MentionQuery } from '../../lib/chatText'
const props = defineProps<{ conversationId: number; label: string; placeholder: string }>()
const emit = defineEmits<{ sent: [] }>()
const { t } = useI18n()
const chat = useChat()
const uid = useId()
const fieldId = `chat-composer-${uid}`
const hintId = `chat-composer-hint-${uid}`
const listId = `chat-mentions-${uid}`
const input = ref<HTMLTextAreaElement | null>(null)
const text = computed({
get: () => chat.drafts.value[props.conversationId] ?? '',
set: (v: string) => (chat.drafts.value[props.conversationId] = v),
const draft = computed(() => chat.draft(props.conversationId))
const errorLine = computed(() => {
const d = draft.value
if (!d.error) return ''
const base = t(`chat.${d.error}`)
return d.detail ? `${base} ${d.detail}` : base
})
const text = computed({
get: () => draft.value.text,
set: (v: string) => {
chat.setDraftText(props.conversationId, v)
// The store throttles to one emit every 3 s and skips blank text.
if (v.trim()) chat.emitTyping(props.conversationId, v)
},
})
const canSend = computed(() => chat.canSend(props.conversationId))
const LINE = 24
function grow() {
const el = input.value
if (!el) return
el.style.height = 'auto'
const cs = getComputedStyle(el)
const pad = parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom)
const max = LINE * 8 + pad
el.style.height = `${Math.min(el.scrollHeight, max)}px`
el.style.overflowY = el.scrollHeight > max ? 'auto' : 'hidden'
}
watch(text, () => void nextTick(grow))
onMounted(grow)
/** At most this many people in the mention list. */
const MENTION_OPTIONS = 6
const mention = ref<MentionQuery | null>(null)
const mentionActive = ref(0)
let dismissedAt: number | null = null
const mentionOptions = computed<ChatMember[]>(() =>
mention.value ? filterMembers(chat.members.values(), mention.value.query, chat.userId).slice(0, MENTION_OPTIONS) : [],
)
/** Without a member list there is no popup; a typed @handle still works on the server. */
const mentionOpen = computed(() => mention.value !== null && chat.membersState === 'ready')
const activeDescendant = computed(() => (mentionOpen.value && mentionOptions.value.length ? `${listId}-opt-${mentionActive.value}` : undefined))
function updateMention() {
const el = input.value
if (!el) return
const q = el.selectionStart === el.selectionEnd ? mentionQuery(el.value, el.selectionStart ?? 0) : null
if (!q) {
dismissedAt = null
mention.value = null
return
}
if (q.start === dismissedAt) return
if (!mention.value || mention.value.start !== q.start || mention.value.query !== q.query) mentionActive.value = 0
mention.value = q
}
function closeMention() {
if (mention.value) dismissedAt = mention.value.start
mention.value = null
}
function pickMention(m: ChatMember) {
const el = input.value
const q = mention.value
if (!el || !q || !m.handle) return
const next = insertMention(el.value, { start: q.start, end: el.selectionStart ?? q.start + q.query.length + 1 }, m.handle)
text.value = next.text
mention.value = null
dismissedAt = null
void nextTick(() => {
el.focus()
el.setSelectionRange(next.caret, next.caret)
})
}
/** The @ button: an @ at the caret (after a space when needed), then the list. */
function startMention() {
const el = input.value
if (!el) return
const start = el.selectionStart ?? el.value.length
const end = el.selectionEnd ?? start
const before = el.value.slice(0, start)
const insert = before === '' || /\s$/.test(before) ? '@' : ' @'
text.value = before + insert + el.value.slice(end)
void chat.loadMembers()
void nextTick(() => {
const caret = start + insert.length
el.focus()
el.setSelectionRange(caret, caret)
dismissedAt = null
updateMention()
})
}
function mentionKey(e: KeyboardEvent): boolean {
if (!mentionOpen.value) return false
const n = mentionOptions.value.length
switch (e.key) {
case 'ArrowDown':
if (n) mentionActive.value = (mentionActive.value + 1) % n
return true
case 'ArrowUp':
if (n) mentionActive.value = (mentionActive.value - 1 + n) % n
return true
case 'Enter':
if (e.shiftKey && !n) return false
if (n) pickMention(mentionOptions.value[mentionActive.value])
else closeMention()
return true
case 'Tab':
if (!n) {
closeMention()
return false
}
pickMention(mentionOptions.value[mentionActive.value])
return true
case 'Escape':
e.stopPropagation()
closeMention()
return true
default:
return false
}
}
watch(
() => props.conversationId,
() => {
mention.value = null
dismissedAt = null
},
)
async function submit() {
await chat.send(text.value)
if (!canSend.value) return
if (await chat.send(props.conversationId)) emit('sent')
}
function onKeydown(e: KeyboardEvent) {
if (e.isComposing || e.key !== 'Enter' || e.shiftKey) return
if (e.isComposing) return
if (mentionKey(e)) {
e.preventDefault()
return
}
if (e.key !== 'Enter' || e.shiftKey) return
e.preventDefault()
void submit()
}
function onKeyup(e: KeyboardEvent) {
if (['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(e.key) || (!mentionOpen.value && ['ArrowUp', 'ArrowDown'].includes(e.key))) updateMention()
}
function focus() {
input.value?.focus()
}
defineExpose({ focus })
</script>
<template>
<form class="chat-composer" @submit.prevent="submit">
<textarea v-model="text" class="chat-composer-input" rows="2" :aria-label="t('chat.message')" :readonly="chat.sending.value" @keydown="onKeydown"></textarea>
<button class="chat-send" type="submit" :disabled="!text.trim() || chat.sending.value">{{ t('chat.send') }}</button>
<label class="chat-sr" :for="fieldId">{{ label }}</label>
<p v-if="errorLine" class="chat-error" role="alert">{{ errorLine }}</p>
<div class="chat-composer-field">
<ChatMentionPopup
v-if="mentionOpen && mention"
:id="listId"
:options="mentionOptions"
:active="mentionActive"
:query="mention.query"
@pick="pickMention"
@hover="mentionActive = $event"
/>
<textarea
:id="fieldId"
ref="input"
v-model="text"
rows="1"
:placeholder="placeholder"
enterkeyhint="send"
:readonly="draft.sending"
:aria-describedby="hintId"
role="combobox"
aria-autocomplete="list"
aria-haspopup="listbox"
:aria-controls="listId"
:aria-expanded="mentionOpen ? 'true' : 'false'"
:aria-activedescendant="activeDescendant"
@keydown="onKeydown"
@keyup="onKeyup"
@input="updateMention"
@click="updateMention"
@blur="mention = null"
></textarea>
<div class="chat-composer-tools">
<button class="chat-icon-btn" type="button" :aria-label="t('chat.composer.mention')" :title="t('chat.composer.mention')" :disabled="draft.sending" @click="startMention">
<ChatIcon name="at" />
</button>
<span class="chat-composer-gap"></span>
<button class="chat-btn chat-btn--primary chat-send" type="submit" :aria-busy="draft.sending ? 'true' : undefined" :disabled="!canSend">
{{ t('chat.send') }}<ChatIcon name="arrow-right" />
</button>
</div>
</div>
<span :id="hintId" class="chat-sr">{{ t('chat.composer.hint') }}</span>
</form>
</template>

View File

@@ -0,0 +1,78 @@
<script setup lang="ts">
// The user's DMs, newest first, and the new-message button (the member
// picker itself lives in ChatPage and the floating panel).
import type { ChatConversationRow } from '../../lib/types'
import { shortName } from '../../lib/chatFormat'
import { badgeText } from '../../lib/chatUnread'
import { dayKey, fmtDateShort, fmtTime } from '../../lib/format'
const emit = defineEmits<{ compose: []; opened: [conversationId: number] }>()
const { t } = useI18n()
const chat = useChat()
const rows = computed(() => chat.dmRows)
const firstLoad = computed(() => !rows.value.length && (chat.bootstrapState === 'loading' || chat.bootstrapState === 'idle'))
const failed = computed(() => !rows.value.length && chat.bootstrapState === 'error')
function name(row: ChatConversationRow) {
return shortName(chat.members.get(row.other_user_id), '', t('chat.someone'))
}
function preview(row: ChatConversationRow) {
const m = row.last_message
if (!m) return ''
return m.sender_id === chat.userId ? t('chat.dm.you', { text: m.content }) : m.content
}
function when(row: ChatConversationRow) {
const at = row.last_message?.created_at
if (!at) return ''
return dayKey(at) === dayKey(new Date()) ? fmtTime(at) : fmtDateShort(at)
}
async function open(row: ChatConversationRow) {
await chat.openDm(row.id)
emit('opened', row.id)
}
</script>
<template>
<section class="chat-dms" :aria-label="t('chat.dm.title')">
<div class="chat-section-head">
<h2 class="chat-section-title">{{ t('chat.dm.title') }}</h2>
<button class="chat-icon-btn" type="button" :aria-label="t('chat.dm.new')" :title="t('chat.dm.new')" @click="emit('compose')"><ChatIcon name="plus" /></button>
</div>
<div v-if="firstLoad" class="chat-skeletons" aria-busy="true" :aria-label="t('chat.loading')">
<div class="chat-skeleton"></div>
<div class="chat-skeleton"></div>
</div>
<p v-else-if="failed" class="chat-error" role="alert">
{{ t('chat.dm.failed') }}
<button class="chat-link-btn" type="button" @click="chat.bootstrap()">{{ t('chat.retry') }}</button>
</p>
<p v-else-if="!rows.length" class="chat-muted chat-dms-empty">{{ t('chat.dm.empty') }}</p>
<ul v-else class="chat-rows">
<li v-for="row in rows" :key="row.id">
<button
class="chat-row chat-dm-row"
:class="{ 'is-unread': row.unread > 0, 'is-active': chat.activeId === row.id }"
type="button"
:aria-current="chat.activeId === row.id ? 'true' : undefined"
@click="open(row)"
>
<ChatAvatar :user-id="row.other_user_id" :member="chat.members.get(row.other_user_id)" :size="24" />
<span class="chat-dm-text">
<span class="chat-row-name">{{ name(row) }}</span>
<span class="chat-dm-preview">{{ preview(row) }}</span>
</span>
<span class="chat-dm-meta">
<time v-if="row.last_message" :datetime="row.last_message.created_at">{{ when(row) }}</time>
<span v-if="badgeText(row.unread)" class="chat-badge"
><span aria-hidden="true">{{ badgeText(row.unread) }}</span><span class="chat-sr">, {{ t('chat.unread.messages', { n: row.unread }, row.unread) }}</span></span
>
</span>
</button>
</li>
</ul>
</section>
</template>

View File

@@ -0,0 +1,94 @@
<script setup lang="ts">
// The open conversation's name, presence (channels) or online dot (DMs),
// the back button of narrow layouts (with the unread count of everything
// else) and the channel's leave action. Under it, the connection strip
// shows whenever realtime is not connected. Presence is not announced to
// screen readers.
import { badgeText } from '../../lib/chatUnread'
import { shortName } from '../../lib/chatFormat'
const props = withDefaults(defineProps<{ back?: boolean }>(), { back: true })
const emit = defineEmits<{ back: [] }>()
const { t } = useI18n()
const chat = useChat()
const channel = computed(() => chat.activeChannel)
const dm = computed(() => chat.activeDm)
const dmName = computed(() => (dm.value ? shortName(chat.members.get(dm.value.other_user_id), '', t('chat.someone')) : ''))
const title = computed(() => (channel.value ? `# ${channel.value.name}` : dmName.value))
const eyebrow = computed(() => (channel.value ? t('chat.header.channel') : t('chat.header.dm')))
/** The connection strip copy; none when connected (or before the chat connects). */
const strip = computed(() => {
switch (chat.connection) {
case 'connecting':
return t('chat.connection.connecting')
case 'reconnecting':
return t('chat.connection.reconnecting')
case 'unavailable':
return t('chat.connection.unavailable')
default:
return ''
}
})
/** What waits elsewhere: unread DMs and mentions outside the open conversation. */
const elsewhere = computed(() => {
const open = chat.activeId
let n = chat.attention
if (open !== null) n -= chat.isChannel(open) ? chat.mentionsOf(open) : chat.unreadOf(open)
return Math.max(0, n)
})
const stack = computed(() => chat.othersOnline.slice(0, 3))
const more = computed(() => Math.max(0, chat.othersOnline.length - 3))
const dmOnline = computed(() => !!dm.value && chat.isOnline(dm.value.other_user_id))
const leaving = ref(false)
async function leave() {
if (!channel.value || leaving.value) return
leaving.value = true
try {
if (await chat.leaveChannel(channel.value)) emit('back')
} finally {
leaving.value = false
}
}
</script>
<template>
<header class="chat-head">
<div class="chat-head-row">
<button v-if="props.back" class="chat-icon-btn chat-back" type="button" :aria-label="t('chat.header.back')" @click="emit('back')">
<ChatIcon name="arrow-left" />
<span v-if="badgeText(elsewhere)" class="chat-badge"
><span aria-hidden="true">{{ badgeText(elsewhere) }}</span><span class="chat-sr">, {{ t('chat.unread.messages', { n: elsewhere }, elsewhere) }}</span></span
>
</button>
<div class="chat-head-name">
<span class="chat-eyebrow">{{ eyebrow }}</span>
<h2 class="chat-title">{{ title }}</h2>
</div>
<div class="chat-presence" aria-hidden="true">
<template v-if="channel && chat.presenceAvailable">
<span v-if="stack.length" class="chat-presence-stack">
<ChatAvatar v-for="id in stack" :key="id" :user-id="id" :member="chat.members.get(id)" :size="24" />
</span>
<span v-if="more" class="chat-presence-text">+{{ more }}</span>
<span class="chat-presence-dot"></span>
<span class="chat-presence-text">{{ chat.onlineCount > 1 ? t('chat.header.online', { n: chat.onlineCount }) : t('chat.header.onlyYou') }}</span>
</template>
<template v-else-if="dmOnline">
<span class="chat-presence-dot"></span>
<span class="chat-presence-text">{{ t('chat.header.dmOnline') }}</span>
</template>
</div>
<div class="chat-head-actions">
<button v-if="channel" class="chat-icon-btn" type="button" :aria-label="t('chat.header.leave')" :title="t('chat.header.leave')" :disabled="leaving" @click="leave">
<ChatIcon name="out" />
</button>
</div>
</div>
</header>
<p v-if="strip" class="chat-strip">{{ strip }}</p>
</template>

View File

@@ -0,0 +1,34 @@
<script setup lang="ts">
// 24x24 stroke icons of the chat (from a Golem15 SPA's Icon.vue, the ones
// the chat uses plus thread, pin and command).
const props = defineProps<{ name: string }>()
const paths: Record<string, string> = {
'arrow-left': 'M19 12H5M11 6l-6 6 6 6',
'arrow-right': 'M5 12h14M13 6l6 6-6 6',
'arrow-up': 'M12 19V5M5 12l7-7 7 7',
'arrow-down': 'M12 5v14M5 12l7 7 7-7',
paperclip: 'M20 11.5l-8.5 8.5a5 5 0 01-7-7L13 4.5a3.5 3.5 0 015 5L9.5 18a2 2 0 01-3-3L14 7.5',
at: 'M12 16a4 4 0 100-8 4 4 0 000 8zM16 12v1.5a2.5 2.5 0 005 0V12a9 9 0 10-3.5 7.1',
smile: 'M12 21a9 9 0 100-18 9 9 0 000 18zM8.5 14.5c1 1.2 2.2 1.8 3.5 1.8s2.5-.6 3.5-1.8M9 9.5h.01M15 9.5h.01',
pencil: 'M4 20h4L19 9l-4-4L4 16zM13.5 6.5l4 4',
trash: 'M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3',
close: 'M6 6l12 12M18 6L6 18',
plus: 'M12 5v14M5 12h14',
file: 'M7 3h7l5 5v13H7zM14 3v5h5M10 13h6M10 17h6',
chat: 'M4 5h16v11H9l-5 4z',
thread: 'M4 5h12v8H8l-4 3zM20 9v9l-3-2h-6',
pin: 'M9 4h6l-1 6 4 3v1H6v-1l4-3zM12 14v6',
slash: 'M16 4L8 20',
link: 'M10 14a4 4 0 005.7 0l3-3a4 4 0 00-5.7-5.7l-1 1M14 10a4 4 0 00-5.7 0l-3 3a4 4 0 005.7 5.7l1-1',
bell: 'M6 16V11a6 6 0 0112 0v5l2 2H4zM10 20h4',
'bell-off': 'M6 16V11a6 6 0 019-5.2M18 11v5l2 2H8M10 20h4M4 4l16 16',
out: 'M10 4H5v16h5M15 8l4 4-4 4M19 12H9',
}
</script>
<template>
<svg class="chat-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path :d="paths[props.name] ?? ''" />
</svg>
</template>

View File

@@ -0,0 +1,94 @@
<script setup lang="ts">
// The new-message dialog: a native modal listing the other members.
// Picking one opens (or creates) the DM; Esc, the backdrop and Close close
// it and return focus to the opener.
import { filterMembers, fullName } from '../../lib/chatFormat'
const emit = defineEmits<{ started: [conversationId: number] }>()
const { t } = useI18n()
const chat = useChat()
const uid = useId()
const dialog = ref<HTMLDialogElement | null>(null)
const search = ref<HTMLInputElement | null>(null)
const q = ref('')
const busy = ref(false)
let opener: HTMLElement | null = null
let picked = false
const others = computed(() => filterMembers(chat.members.values(), '', chat.userId))
const results = computed(() => filterMembers(chat.members.values(), q.value, chat.userId))
function open() {
opener = document.activeElement instanceof HTMLElement ? document.activeElement : null
picked = false
q.value = ''
chat.dmError = ''
void chat.loadMembers()
dialog.value?.showModal()
void nextTick(() => search.value?.focus())
}
function close() {
dialog.value?.close()
}
function onClose() {
if (!picked) opener?.focus()
opener = null
}
function onBackdrop(e: MouseEvent) {
if (e.target === dialog.value) close()
}
async function pick(id: number) {
if (busy.value) return
busy.value = true
try {
const conversationId = await chat.startDm(id)
if (conversationId === null) return
picked = true
close()
emit('started', conversationId)
} finally {
busy.value = false
}
}
defineExpose({ open })
</script>
<template>
<dialog ref="dialog" class="chat-dialog" :aria-labelledby="`chat-picker-h-${uid}`" @close="onClose" @click="onBackdrop">
<div class="chat-dialog-head">
<h2 :id="`chat-picker-h-${uid}`" class="chat-dialog-title">{{ t('chat.dm.new') }}</h2>
<button class="chat-icon-btn" type="button" :aria-label="t('chat.close')" @click="close"><ChatIcon name="close" /></button>
</div>
<div class="chat-field">
<label :for="`chat-picker-q-${uid}`">{{ t('chat.picker.to') }}</label>
<input :id="`chat-picker-q-${uid}`" ref="search" v-model="q" type="text" autocomplete="off" :placeholder="t('chat.picker.placeholder')" />
</div>
<p v-if="chat.dmError" class="chat-error" role="alert">{{ t(`chat.${chat.dmError}`) }}</p>
<div class="chat-picker-results">
<div v-if="chat.membersState === 'loading' && !chat.members.size" class="chat-skeletons" aria-busy="true" :aria-label="t('chat.loading')">
<div class="chat-skeleton"></div>
<div class="chat-skeleton"></div>
</div>
<p v-else-if="chat.membersState === 'error' && !chat.members.size" class="chat-error" role="alert">
{{ t('chat.picker.failed') }}
<button class="chat-link-btn" type="button" @click="chat.loadMembers(true)">{{ t('chat.retry') }}</button>
</p>
<p v-else-if="!others.length" class="chat-muted">{{ t('chat.picker.nobody') }}</p>
<p v-else-if="!results.length" class="chat-muted">{{ t('chat.picker.noMatch', { q: q.trim() }) }}</p>
<ul v-else class="chat-rows">
<li v-for="m in results" :key="m.id">
<button class="chat-row chat-picker-row" type="button" :disabled="busy" @click="pick(m.id)">
<ChatAvatar :user-id="m.id" :member="m" :size="24" />
<span class="chat-row-name">{{ fullName(m) }}</span>
<span class="chat-pop-meta">@{{ m.handle }}</span>
</button>
</li>
</ul>
</div>
</dialog>
</template>

View File

@@ -0,0 +1,38 @@
<script setup lang="ts">
// The listbox of the composer's mention combobox. The textarea keeps focus;
// it points at the active option through aria-activedescendant, so every
// option has a stable id. Options are picked with mousedown so the textarea
// never loses focus.
import type { ChatMember } from '../../lib/types'
import { fullName } from '../../lib/chatFormat'
defineProps<{ id: string; options: ChatMember[]; active: number; query: string }>()
const emit = defineEmits<{ pick: [member: ChatMember]; hover: [index: number] }>()
const { t } = useI18n()
/** The id of option i; the composer builds the same id for aria-activedescendant. */
function optionId(listId: string, i: number): string {
return `${listId}-opt-${i}`
}
</script>
<template>
<ul :id="id" class="chat-pop chat-mention-pop" role="listbox" :aria-label="t('chat.mention.label')">
<li v-if="!options.length" class="chat-pop-empty" role="option" aria-disabled="true" aria-selected="false">{{ t('chat.mention.none', { q: query }) }}</li>
<li
v-for="(m, i) in options"
:id="optionId(id, i)"
:key="m.id"
class="chat-pop-option"
:class="{ 'is-active': i === active }"
role="option"
:aria-selected="i === active ? 'true' : 'false'"
@mousedown.prevent="emit('pick', m)"
@mousemove="i !== active && emit('hover', i)"
>
<ChatAvatar :user-id="m.id" :member="m" :size="24" />
<span class="chat-pop-name">{{ fullName(m) }}</span>
<span class="chat-pop-meta">@{{ m.handle }}</span>
</li>
</ul>
</template>

View File

@@ -0,0 +1,49 @@
<script setup lang="ts">
// One message, left-aligned with the author's initials. The body goes
// through renderChatText only (escape-first inline markdown, autolinks and
// member mentions); it is the only HTML binding of the layer. Names and
// every other field are text bindings.
import type { ChatMember, ChatMessage } from '../../lib/types'
import { shortName } from '../../lib/chatFormat'
import { mentionsHandle, renderChatText } from '../../lib/chatText'
import { fmtDateTime, fmtTime } from '../../lib/format'
const props = defineProps<{ message: ChatMessage; followUp?: boolean; author?: ChatMember | null; meId: number | null }>()
const { t } = useI18n()
const chat = useChat()
const mine = computed(() => props.meId !== null && props.message.sender_id === props.meId)
const name = computed(() => shortName(props.author, props.message.sender_name, t('chat.someone')))
const time = computed(() => fmtTime(props.message.created_at))
const timeTitle = computed(() => fmtDateTime(props.message.created_at))
const isBot = computed(() => !!props.author?.is_bot)
/** Someone else's message that mentions you gets the accent marker. */
const mentionsMe = computed(() => !mine.value && mentionsHandle(props.message.content, chat.myHandle))
const editedTitle = computed(() => (props.message.edited_at ? t('chat.msg.editedAt', { at: fmtDateTime(props.message.edited_at) }) : ''))
const deleted = computed(() => !!props.message.deleted_at)
const rendered = computed(() => renderChatText(props.message.content, chat.membersByHandle))
</script>
<template>
<article class="chat-msg" :class="{ 'is-follow': followUp, 'is-mention': mentionsMe }" :data-message-id="message.id">
<div class="chat-msg-gutter">
<ChatAvatar v-if="!followUp" :user-id="message.sender_id" :member="author" :fallback="message.sender_name" :me="mine" />
<time v-else class="chat-msg-time" :datetime="message.created_at" :title="timeTitle">{{ time }}</time>
</div>
<div class="chat-msg-content">
<div v-if="!followUp" class="chat-msg-head">
<span class="chat-msg-name">{{ name }}</span>
<span v-if="isBot" class="chat-tag">{{ t('chat.msg.bot') }}</span>
<span v-else-if="mine" class="chat-tag chat-tag--me">{{ t('chat.msg.you') }}</span>
<time class="chat-msg-time" :datetime="message.created_at" :title="timeTitle">{{ time }}</time>
<span v-if="message.edited_at" class="chat-msg-edited" :title="editedTitle">{{ t('chat.msg.edited') }}</span>
</div>
<span v-else class="chat-sr">{{ name }}, {{ time }}:</span>
<p v-if="deleted" class="chat-msg-deleted">{{ t('chat.msg.deleted') }}</p>
<template v-else>
<div v-if="message.content" class="chat-msg-body" v-html="rendered"></div>
<span v-if="followUp && message.edited_at" class="chat-msg-edited" :title="editedTitle">{{ t('chat.msg.edited') }}</span>
</template>
</div>
</article>
</template>

View File

@@ -1,16 +1,301 @@
<script setup lang="ts">
// The messages of one conversation, oldest first, as plain text.
const props = defineProps<{ conversationId: number }>()
// The messages of one conversation, with day separators and grouping. It is
// the only scrolling region of the conversation.
//
// The conversation is marked read only while it is active, on screen, the
// window has focus and the list is at the bottom. "New messages" marks the
// first unread message from someone else when the conversation is opened,
// and stays until it changes. Older pages load from a top sentinel,
// keeping the first message where it was.
import type { ChatAnchor } from '../../composables/useChat'
import { groupMessages, shortName } from '../../lib/chatFormat'
import { dividerMessageId, shouldMarkRead } from '../../lib/chatUnread'
const props = withDefaults(defineProps<{ conversationId: number; name: string; kind?: 'channel' | 'dm'; otherName?: string; visible?: boolean }>(), {
kind: 'channel',
otherName: '',
visible: true,
})
const { t } = useI18n()
const chat = useChat()
const list = computed(() => chat.messages.value[props.conversationId] ?? [])
const el = ref<HTMLElement | null>(null)
const sentinel = ref<HTMLElement | null>(null)
const list = computed(() => chat.messages[props.conversationId])
const error = computed(() => chat.errors[props.conversationId] ?? '')
const dayLabels = computed(() => ({ today: t('chat.day.today'), yesterday: t('chat.day.yesterday') }))
const items = computed(() => groupMessages(list.value ?? [], new Date(), dayLabels.value))
const lastId = computed(() => list.value?.at(-1)?.id ?? null)
const olderLoading = computed(() => !!chat.olderLoading[props.conversationId])
const olderError = computed(() => chat.olderError[props.conversationId] ?? '')
const atStart = computed(() => !!chat.reachedStart[props.conversationId])
const startCopy = computed(() => (props.kind === 'dm' ? t('chat.list.startDm', { name: props.otherName }) : t('chat.list.startChannel', { name: props.name })))
/** The unread count when this conversation was opened (the list mounts per conversation). */
const unreadAtOpen = chat.unreadOf(props.conversationId)
const dividerId = ref<number | null>(null)
let dividerSet = false
function placeDivider() {
if (dividerSet || !list.value) return
dividerSet = true
dividerId.value = dividerMessageId(list.value, unreadAtOpen, chat.userId)
}
/** Messages from others that arrived while scrolled up. */
const pending = ref(0)
/** The sr-only announcement of the last message from someone else. */
const announcement = ref('')
const reduceMotion = typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches
/** Laid out (not under display: none). */
function shown(): boolean {
return !!el.value && el.value.clientHeight > 0
}
/** Within 48px of the bottom counts as at the bottom. */
function atBottom(): boolean {
const e = el.value
return !e || e.scrollHeight - e.scrollTop - e.clientHeight <= 48
}
function firstVisible(): ChatAnchor | null {
const e = el.value
if (!e) return null
for (const n of e.querySelectorAll<HTMLElement>('[data-message-id]')) {
if (n.offsetTop + n.offsetHeight > e.scrollTop) {
return { atBottom: false, messageId: Number(n.dataset.messageId), offset: n.offsetTop - e.scrollTop }
}
}
return null
}
function capture(): ChatAnchor | null {
const e = el.value
if (!e || !shown() || !list.value) return null
if (atBottom()) return { atBottom: true, messageId: null, offset: 0 }
return firstVisible() ?? { atBottom: true, messageId: null, offset: 0 }
}
function save() {
const a = capture()
if (a) chat.saveAnchor(props.conversationId, a)
}
let stuck = true
const placed = ref(false)
function checkRead() {
if (!list.value || !shown()) return
const seen = shouldMarkRead({
active: chat.activeId === props.conversationId,
visible: props.visible,
focused: typeof document === 'undefined' || document.hasFocus(),
atBottom: atBottom(),
})
if (seen) chat.markRead(props.conversationId)
}
function scrollToBottom(smooth = false) {
void nextTick(() => {
const e = el.value
if (!e) return
if (smooth && !reduceMotion && typeof e.scrollTo === 'function') e.scrollTo({ top: e.scrollHeight, behavior: 'smooth' })
else e.scrollTop = e.scrollHeight
stuck = true
pending.value = 0
if (shown()) chat.saveAnchor(props.conversationId, { atBottom: true, messageId: null, offset: 0 })
checkRead()
})
}
function toDivider(e: HTMLElement): boolean {
if (dividerId.value === null) return false
const d = e.querySelector<HTMLElement>('.chat-new')
if (!d) return false
const bottomTop = e.scrollHeight - e.clientHeight
if (d.offsetTop >= bottomTop) return false
e.scrollTop = d.offsetTop - 48
return true
}
function restore() {
void nextTick(() => {
const e = el.value
if (!e || !shown() || !list.value) return
placeDivider()
void nextTick(() => {
const a = chat.anchorFor(props.conversationId)
const target = a && !a.atBottom && a.messageId !== null ? e.querySelector<HTMLElement>(`[data-message-id="${a.messageId}"]`) : null
if (!target) {
if (!(dividerId.value !== null && !placed.value && toDivider(e))) e.scrollTop = e.scrollHeight
} else {
e.scrollTop = target.offsetTop - (a?.offset ?? 0)
}
stuck = atBottom()
if (stuck) pending.value = 0
placed.value = true
checkRead()
recheckSentinel()
})
})
}
let frame = 0
function onScroll() {
stuck = atBottom()
if (stuck) pending.value = 0
if (frame) return
frame = requestAnimationFrame(() => {
frame = 0
save()
checkRead()
})
}
watch(
() => list.value === undefined,
(missing, was) => {
if (!missing && was) restore()
},
)
// A new last message: your own always scrolls to it, others' only while at
// the bottom; otherwise the pill counts them. Older pages never change lastId.
watch(lastId, (id, old) => {
if (id === null || id === old || old === null) return
const all = list.value ?? []
const fresh = all.filter((m) => m.id > old)
const last = all.at(-1)
const others = fresh.filter((m) => m.sender_id !== chat.userId)
const latest = others.at(-1)
if (latest && props.visible) {
const body = (latest.content ?? '').replace(/\s+/g, ' ').trim().slice(0, 80)
announcement.value = `${shortName(chat.members.get(latest.sender_id), latest.sender_name, t('chat.someone'))}: ${body}`
}
if (stuck || (last && last.sender_id === chat.userId)) scrollToBottom()
else pending.value += others.length
})
watch(
() => props.visible,
(v, old) => {
if (old && !v) save()
if (v && !old) restore()
},
)
let observer: IntersectionObserver | null = null
async function older() {
const e = el.value
if (!e || !placed.value || olderLoading.value || olderError.value || atStart.value) return
const keep = firstVisible()
await chat.loadOlder(props.conversationId)
await nextTick()
if (keep?.messageId != null) {
const n = e.querySelector<HTMLElement>(`[data-message-id="${keep.messageId}"]`)
if (n) e.scrollTop = n.offsetTop - keep.offset
}
recheckSentinel()
}
function recheckSentinel() {
const n = sentinel.value
if (!observer || !n) return
observer.unobserve(n)
observer.observe(n)
}
function retryOlder() {
chat.olderError[props.conversationId] = ''
void nextTick(() => void older())
}
watch(sentinel, (n, prev) => {
if (prev) observer?.unobserve(prev)
if (n) observer?.observe(n)
})
function onFocus() {
checkRead()
}
function onVisibility() {
if (document.visibilityState === 'visible') checkRead()
}
onMounted(() => {
if (typeof IntersectionObserver !== 'undefined' && el.value) {
observer = new IntersectionObserver(
(entries) => {
if (entries.some((x) => x.isIntersecting)) void older()
},
{ root: el.value, rootMargin: '200px 0px 0px 0px' },
)
if (sentinel.value) observer.observe(sentinel.value)
}
window.addEventListener('focus', onFocus)
document.addEventListener('visibilitychange', onVisibility)
restore()
})
onBeforeUnmount(() => {
if (frame) cancelAnimationFrame(frame)
observer?.disconnect()
window.removeEventListener('focus', onFocus)
document.removeEventListener('visibilitychange', onVisibility)
save()
})
defineExpose({ scrollToBottom })
</script>
<template>
<div class="chat-list" role="log" :aria-label="t('chat.messages')">
<article v-for="m in list" :key="m.id" class="chat-msg" :data-message-id="m.id">
<span class="chat-msg-name">{{ m.sender_name }}</span>
<p class="chat-msg-body">{{ m.content }}</p>
</article>
<div class="chat-list-wrap">
<div ref="el" class="chat-list" role="region" :aria-label="t('chat.list.label', { name })" tabindex="0" @scroll.passive="onScroll">
<p v-if="!list && error" class="chat-error" role="alert">
{{ t(`chat.${error}`) }}
<button class="chat-link-btn" type="button" @click="chat.loadLatest(conversationId)">{{ t('chat.retry') }}</button>
</p>
<div v-else-if="!list" class="chat-skeletons" aria-busy="true" :aria-label="t('chat.loading')">
<div class="chat-skeleton"></div>
<div class="chat-skeleton"></div>
<div class="chat-skeleton"></div>
</div>
<p v-else-if="!list.length" class="chat-start">{{ startCopy }}</p>
<template v-else>
<div ref="sentinel" class="chat-older">
<p v-if="olderError" class="chat-error">
{{ t(`chat.${olderError}`) }}
<button class="chat-link-btn" type="button" @click="retryOlder">{{ t('chat.retry') }}</button>
</p>
<p v-else-if="olderLoading" class="chat-start">{{ t('chat.list.olderLoading') }}</p>
<p v-else-if="atStart" class="chat-start">{{ startCopy }}</p>
</div>
<template v-for="item in items" :key="item.key">
<div v-if="item.kind === 'day'" class="chat-day" role="separator" :aria-label="item.label">
<span aria-hidden="true">{{ item.label }}</span>
</div>
<template v-else>
<div v-if="item.message.id === dividerId" class="chat-new" role="separator" :aria-label="t('chat.list.new')">
<span aria-hidden="true">{{ t('chat.list.new') }}</span>
</div>
<ChatMessage
:message="item.message"
:follow-up="item.followUp && item.message.id !== dividerId"
:author="chat.members.get(item.message.sender_id)"
:me-id="chat.userId"
/>
</template>
</template>
</template>
</div>
<button v-if="pending > 0" class="chat-btn chat-btn--small chat-jump" type="button" @click="scrollToBottom(true)">
<ChatIcon name="arrow-down" />{{ t('chat.list.jump', { n: pending }) }}
</button>
<div class="chat-sr" aria-live="polite">{{ announcement }}</div>
</div>
</template>

View File

@@ -0,0 +1,14 @@
<script setup lang="ts">
// The chat's short notices (useChatNotice), announced politely.
const { t } = useI18n()
const notice = useChatNotice()
</script>
<template>
<div class="chat-notices" role="status" aria-live="polite">
<p v-if="notice.current.value" class="chat-notice">
{{ t(`chat.${notice.current.value.key}`, notice.current.value.params ?? {}) }}
<button class="chat-icon-btn" type="button" :aria-label="t('chat.close')" @click="notice.clear()"><ChatIcon name="close" /></button>
</p>
</div>
</template>

View File

@@ -1,26 +1,45 @@
<script setup lang="ts">
// The full chat: the channel sidebar and the open conversation. Render it
// inside <ClientOnly> (it uses window and the DOM).
const { t } = useI18n()
// The full chat: a sidebar with the channels and the DMs, and the open
// conversation. On a narrow screen one of them shows at a time. Render it
// inside <ClientOnly> (it uses window and the DOM); it starts the chat
// store itself.
//
// Slots: sidebar-footer (below the channel list).
const { t, locale, localeProperties } = useI18n()
const chat = useChat()
const picker = ref<{ open: () => void } | null>(null)
const panel = ref<{ focus: () => void } | null>(null)
const formatLocale = computed(() => (localeProperties.value as { language?: string } | undefined)?.language || locale.value)
onMounted(() => {
void chat.start()
void chat.start(formatLocale.value)
})
const active = computed(() => chat.channels.value.find((c) => c.conversation_id === chat.activeId.value) ?? null)
const open = computed(() => chat.activeId !== null)
function opened() {
panel.value?.focus()
}
</script>
<template>
<div class="chat-page">
<ChatChannelList />
<section class="chat-pane" :aria-label="active ? `# ${active.name}` : t('chat.name')">
<template v-if="chat.activeId.value !== null">
<ChatMessageList :conversation-id="chat.activeId.value" />
<ChatComposer :conversation-id="chat.activeId.value" />
</template>
<p v-else class="chat-pane-empty">{{ t('chat.pickChannel') }}</p>
<p v-if="chat.error.value" class="chat-error" role="alert">{{ t(`chat.error.${chat.error.value}`) }}</p>
</section>
<div class="chat-page" :class="{ 'is-open': open }">
<p v-if="chat.bootstrapState === 'error' && chat.member === undefined" class="chat-error" role="alert">
{{ t('chat.error.bootstrap') }}
<button class="chat-link-btn" type="button" @click="chat.start(formatLocale)">{{ t('chat.retry') }}</button>
</p>
<p v-else-if="chat.member === false" class="chat-muted">{{ t('chat.notMember') }}</p>
<template v-else>
<aside class="chat-sidebar">
<ChatChannelList @opened="opened">
<template #sidebar-footer><slot name="sidebar-footer" /></template>
</ChatChannelList>
<ChatDmList @compose="picker?.open()" @opened="opened" />
</aside>
<ChatPanel ref="panel" class="chat-main" @back="chat.close()" />
<ChatMemberPicker ref="picker" @started="opened" />
</template>
<ChatNotices />
</div>
</template>

View File

@@ -0,0 +1,69 @@
<script setup lang="ts">
// The open conversation: header, messages, the typing line and the
// composer. With nothing open it shows the empty state.
import { shortName } from '../../lib/chatFormat'
const props = withDefaults(defineProps<{ visible?: boolean; back?: boolean }>(), { visible: true, back: true })
const emit = defineEmits<{ back: [] }>()
const { t } = useI18n()
const chat = useChat()
const list = ref<{ scrollToBottom: (smooth?: boolean) => void } | null>(null)
const composer = ref<{ focus: () => void } | null>(null)
const dmName = computed(() => (chat.activeDm ? shortName(chat.members.get(chat.activeDm.other_user_id), '', t('chat.someone')) : ''))
const name = computed(() => (chat.activeChannel ? `# ${chat.activeChannel.name}` : dmName.value))
/** Who is typing in the open conversation; empty without realtime. */
const typingLine = computed(() => {
const id = chat.activeId
if (id === null) return ''
const names = chat.typingIn(id).map((u) => shortName(chat.members.get(u), '', t('chat.someone')))
if (!names.length) return ''
if (names.length === 1) return t('chat.typing.one', { a: names[0] })
if (names.length === 2) return t('chat.typing.two', { a: names[0], b: names[1] })
return t('chat.typing.many')
})
// The store needs to know whether the conversation is on screen.
watch(
() => props.visible,
(v) => (chat.panelVisible = v),
{ immediate: true },
)
onBeforeUnmount(() => (chat.panelVisible = false))
function focus() {
void nextTick(() => composer.value?.focus())
}
defineExpose({ focus })
</script>
<template>
<section class="chat-panel" :aria-label="name || t('chat.name')">
<template v-if="chat.activeId !== null && chat.kind">
<ChatHeader :back="back" @back="emit('back')" />
<ChatMessageList
ref="list"
:key="chat.activeId"
:conversation-id="chat.activeId"
:name="name"
:kind="chat.kind"
:other-name="dmName"
:visible="visible"
/>
<div class="chat-typing" aria-hidden="true">{{ typingLine }}</div>
<ChatComposer
ref="composer"
:key="`c-${chat.activeId}`"
:conversation-id="chat.activeId"
:label="t('chat.composer.label', { name })"
:placeholder="t('chat.composer.placeholder', { name })"
@sent="list?.scrollToBottom()"
/>
</template>
<div v-else class="chat-panel-empty">
<p class="chat-panel-empty-title">{{ t('chat.pickTitle') }}</p>
<p class="chat-muted">{{ t('chat.pickText') }}</p>
</div>
</section>
</template>

File diff suppressed because it is too large Load Diff

View File

@@ -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<string, unknown>
}
export function useChatNotice() {
const current = useState<ChatNotice | null>('chat:notice', () => null)
const nuxtApp = useNuxtApp() as unknown as { _chatNoticeTimer?: ReturnType<typeof setTimeout> }
function show(key: string, params?: Record<string, unknown>, 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 }
}

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