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>