Files
vue-chat-layer/app/components/Chat/MessageList.vue
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

302 lines
10 KiB
Vue

<script setup lang="ts">
// 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 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-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>