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

238 lines
7.3 KiB
Vue

<script setup lang="ts">
// 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 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() {
if (!canSend.value) return
if (await chat.send(props.conversationId)) emit('sent')
}
function onKeydown(e: KeyboardEvent) {
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">
<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>