Files
vue-chat-layer/app/components/Chat/Composer.vue
Jakub Zych 269c75b5dd feat: threads, pins, reactions, attachments, link embeds and the command picker
- threads: reply counts, ChatThreadPane with replies, live replies and thread mute
- channel pins in ChatPinsPanel; a refused pin hides the action for the session
- reactions, attachments with upload progress and bearer downloads, inline edits, the delete dialog (moderators also in channels)
- link cards with the registerEmbedRenderer registry; linkify for escaped text
- slash commands: the command picker over chatbots, dispatch with sender-only answers
- slots conversation-actions (DMs only) and sidebar-footer
- chat-tokens.css and chat-base.css, EN and PL copy, README
2026-10-31 14:04:54 +01:00

347 lines
11 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.
//
// Slash commands: a "/" at the start of the text opens the command list
// (golem15.chatbots' catalog, loaded once a session) filtered by what
// follows it. Picking one runs it; sending any text that starts with "/"
// runs it too (the store dispatches it instead of posting it). The answer
// shows under the conversation, to the sender only.
//
// Attachments: the paperclip picks files, which upload at once with
// progress; the send waits for them.
import type { ChatCommand, ChatMember } from '../../lib/types'
import { filterMembers } from '../../lib/chatFormat'
import { insertMention, mentionQuery, type MentionQuery } from '../../lib/chatText'
import type { FileCheckMessages } from '../../lib/attachments'
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 commandListId = `chat-commands-${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 fileInput = ref<HTMLInputElement | null>(null)
const fileMessages: FileCheckMessages = {
tooLarge: (name, mb) => t('chat.files.tooLarge', { name, mb }),
overTotal: (mb) => t('chat.files.overTotal', { mb }),
banned: () => t('chat.files.banned'),
tooMany: (max) => t('chat.files.tooMany', { n: max }),
}
function pickFiles() {
if (draft.value.sending) return
fileInput.value?.click()
}
function onFiles() {
const el = fileInput.value
if (!el?.files?.length) return
chat.uploadFiles(props.conversationId, [...el.files], fileMessages)
// The same file can be picked again after a removal.
el.value = ''
void nextTick(focus)
}
/** The command query: what follows a "/" at the start of the text, until a space. */
const commandQuery = computed(() => {
const m = /^\/(\S*)$/.exec(text.value)
return m ? m[1] : null
})
const commandActive = ref(0)
const commandDismissed = ref(false)
const commandOptions = computed<ChatCommand[]>(() => {
const q = commandQuery.value
if (q === null) return []
const lower = q.toLowerCase()
return (chat.commands ?? []).filter((c) => c.trigger.toLowerCase().startsWith(lower))
})
const commandOpen = computed(() => commandQuery.value !== null && !commandDismissed.value)
watch(commandQuery, (q, old) => {
if (q === null) {
commandDismissed.value = false
return
}
if (old === null) void chat.loadCommands()
if (q !== old) commandActive.value = 0
})
async function pickCommand(c: ChatCommand) {
commandDismissed.value = false
if (await chat.runCommand(props.conversationId, `/${c.trigger}`)) {
chat.setDraftText(props.conversationId, '')
emit('sent')
}
void nextTick(focus)
}
function commandKey(e: KeyboardEvent): boolean {
if (!commandOpen.value) return false
const n = commandOptions.value.length
switch (e.key) {
case 'ArrowDown':
if (n) commandActive.value = (commandActive.value + 1) % n
return true
case 'ArrowUp':
if (n) commandActive.value = (commandActive.value - 1 + n) % n
return true
case 'Enter':
case 'Tab':
if (!n || e.shiftKey) return false
void pickCommand(commandOptions.value[commandActive.value])
return true
case 'Escape':
e.stopPropagation()
commandDismissed.value = true
return true
default:
return false
}
}
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(() => {
if (commandOpen.value && commandOptions.value.length) return `${commandListId}-opt-${commandActive.value}`
return 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 (commandKey(e) || 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>
<ChatStagingChips :conversation-id="conversationId" @removed="focus" />
<div class="chat-composer-field">
<ChatCommandPicker
v-if="commandOpen && commandQuery !== null"
:id="commandListId"
:options="commandOptions"
:active="commandActive"
:query="commandQuery"
:loading="chat.commands === null"
@pick="pickCommand"
@hover="commandActive = $event"
/>
<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="commandOpen ? commandListId : listId"
:aria-expanded="mentionOpen || commandOpen ? '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.files.attach')" :title="t('chat.files.attach')" :disabled="draft.sending" @click="pickFiles">
<ChatIcon name="paperclip" />
</button>
<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>
<input ref="fileInput" class="chat-sr" type="file" multiple tabindex="-1" aria-hidden="true" @change="onFiles" />
</form>
</template>