GhostChatMessage
GhostChatMessage is one message in a conversation: who sent it, which side it sits on, its content, and whether it is still arriving. Import it from @ghostvue/themes for chat bubbles. A whole chat view is composed from it, GhostScrollArea with stickToBottom, and GhostTextarea with submitOnEnter, as the next example shows. To style messages yourself, see Advanced: headless composition.
Build a chat
Log that follows a streamed reply, stops when the reader scrolls up, offers Jump to latest with an unread count, and announces arrivals in one status region.
Support chat
- Hi! How can I help with your workspace today?
- YOYouOur nightly report export did not arrive this morning.
- ASAssistantSorry about that. Which workspace is it, and when did the last export arrive?
- YOYouWorkspace "Northwind ops". The last one came on Sunday night.
- ASAssistantThanks. Is anything else failing, or only the export?
- YOYouOnly the export. Dashboards still load fine.
<script setup lang="ts">
import { onBeforeUnmount, ref, useId, useTemplateRef } from 'vue'
import { GhostVisuallyHidden } from '@ghostvue/vue'
import {
GhostAvatar,
GhostButton,
GhostChatMessage,
GhostCheckbox,
GhostInlineAlert,
GhostScrollArea,
GhostTextarea,
type GhostChatMessageStatus,
type GhostTextareaExposed,
} from '@ghostvue/themes'
interface ChatMessage {
id: number
author: string
mine: boolean
status: GhostChatMessageStatus
text: string
at: string
failed?: boolean
}
const ASSISTANT = 'Assistant'
const ME = 'You'
const REPLY =
'Thanks for the details. I checked your workspace: the nightly export ' +
'stopped after the storage key was rotated on Monday. Open Settings, then ' +
'Integrations, and reconnect the storage bucket with the new key. The next ' +
'export runs at 02:00 UTC and will include every report you missed this ' +
'week. Reply here if the export still fails after that.'
/** Milliseconds between simulated chunks of a streamed reply. */
const CHUNK_MS = 120
const headingId = useId()
const hintId = useId()
let nextId = 1
const messages = ref<ChatMessage[]>([
message(ASSISTANT, false, 'Hi! How can I help with your workspace today?'),
message(ME, true, 'Our nightly report export did not arrive this morning.'),
message(
ASSISTANT,
false,
'Sorry about that. Which workspace is it, and when did the last export arrive?',
),
message(
ME,
true,
'Workspace "Northwind ops". The last one came on Sunday night.',
),
message(
ASSISTANT,
false,
'Thanks. Is anything else failing, or only the export?',
),
message(ME, true, 'Only the export. Dashboards still load fine.'),
])
const draft = ref('')
const sending = ref(false)
const following = ref(true)
const unread = ref(0)
const announcement = ref('')
const dropNextReply = ref(false)
const composer = useTemplateRef<GhostTextareaExposed>('composer')
const timers = new Set<ReturnType<typeof setTimeout>>()
function later(callback: () => void, delay: number): void {
const timer = setTimeout(() => {
timers.delete(timer)
callback()
}, delay)
timers.add(timer)
}
onBeforeUnmount(() => {
for (const timer of timers) clearTimeout(timer)
timers.clear()
})
function message(
author: string,
mine: boolean,
text: string,
status: GhostChatMessageStatus = 'complete',
): ChatMessage {
const minutes = 30 + nextId
return {
id: nextId++,
author,
mine,
status,
text,
at: `2026-03-02T09:${String(minutes).padStart(2, '0')}:00Z`,
}
}
const timeFormat = new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
minute: '2-digit',
timeZone: 'UTC',
})
function formatTime(iso: string): string {
return timeFormat.format(new Date(iso))
}
function nowIso(): string {
return new Date().toISOString()
}
let clearAnnouncement: ReturnType<typeof setTimeout> | undefined
/**
* One polite status region for the whole log. Each announcement is a fresh
* change (clear, then write on a later tick), so two identical messages in a
* row are both spoken, and it is cleared again so browse mode does not find
* a stale copy after the log.
*/
function announce(text: string): void {
announcement.value = ''
if (clearAnnouncement) clearTimeout(clearAnnouncement)
later(() => {
announcement.value = text
clearAnnouncement = setTimeout(() => {
announcement.value = ''
}, 5000)
timers.add(clearAnnouncement)
}, 100)
}
function preview(text: string): string {
const words = text.split(/\s+/).slice(0, 6).join(' ')
return `${words}…`
}
function send(): void {
const text = draft.value.trim()
if (!text || sending.value) return
messages.value.push({ ...message(ME, true, text), at: nowIso() })
draft.value = ''
sending.value = true
// The user's own message is not announced; they just typed it.
later(startReply, 600)
}
function startReply(): void {
sending.value = false
const reply: ChatMessage = {
...message(ASSISTANT, false, '', 'typing'),
at: nowIso(),
}
messages.value.push(reply)
announce(`${ASSISTANT} is replying`)
const words = REPLY.split(' ')
const drop = dropNextReply.value
dropNextReply.value = false
let index = 0
const findReply = (): ChatMessage | undefined =>
messages.value.find((entry) => entry.id === reply.id)
const streamNext = (): void => {
const current = findReply()
if (!current) return
if (drop && index === 12) {
current.status = 'complete'
current.failed = true
// Replaces this message's arrival announcement.
announce('Reply failed')
return
}
if (index >= words.length) {
current.status = 'complete'
announce(`${ASSISTANT} replied: ${preview(current.text)}`)
if (!following.value) unread.value += 1
return
}
current.status = 'streaming'
current.text =
index === 0 ? (words[0] ?? '') : `${current.text} ${words[index] ?? ''}`
index += 1
later(streamNext, CHUNK_MS)
}
later(streamNext, 900)
}
function jumpToLatest(event: MouseEvent): void {
const button = event.currentTarget
// Keyboard activation moves focus to the composer before the button hides;
// a click or tap leaves focus alone so no virtual keyboard opens.
if (button instanceof HTMLElement && button.matches(':focus-visible')) {
composer.value?.focus()
}
// Setting the model scrolls to the bottom instantly and resumes following.
following.value = true
unread.value = 0
}
</script>
<template>
<section class="chat" :aria-labelledby="headingId">
<h2 :id="headingId" class="chat__title">Support chat</h2>
<div class="chat__log-frame">
<GhostScrollArea
v-model:stuck="following"
stick-to-bottom
label="Conversation"
class="chat__log"
>
<ol class="chat__messages" role="list">
<li v-for="entry in messages" :key="entry.id">
<GhostChatMessage
:side="entry.mine ? 'end' : 'start'"
:status="entry.status"
:typing-label="`${entry.author} is typing`"
>
<template #avatar>
<GhostAvatar
:name="entry.author"
size="sm"
aria-hidden="true"
/>
</template>
<template #header>
<span class="chat__author">{{ entry.author }}</span>
<time :datetime="entry.at">{{ formatTime(entry.at) }}</time>
</template>
<span class="chat__text">{{ entry.text }}</span>
<template v-if="entry.failed" #footer>
<GhostInlineAlert tone="danger">
<template #message>
Reply interrupted. Ask again to get the full answer.
</template>
</GhostInlineAlert>
</template>
</GhostChatMessage>
</li>
</ol>
</GhostScrollArea>
<GhostButton
v-if="!following"
class="chat__jump"
size="sm"
variant="soft"
tone="neutral"
@click="jumpToLatest"
>
Jump to latest<template v-if="unread"> ({{ unread }} new)</template>
</GhostButton>
</div>
<GhostVisuallyHidden role="status" aria-atomic="true">
{{ announcement }}
</GhostVisuallyHidden>
<form class="chat__composer" @submit.prevent="send">
<GhostTextarea
ref="composer"
v-model="draft"
class="chat__input"
submit-on-enter
auto-resize
:rows="1"
:max-rows="6"
:readonly="sending"
enterkeyhint="send"
aria-label="Message"
:aria-describedby="hintId"
/>
<GhostButton type="submit" :loading="sending">Send</GhostButton>
<p :id="hintId" class="chat__hint">
Enter to send, Shift+Enter for a new line
</p>
</form>
<label class="chat__option">
<GhostCheckbox v-model="dropNextReply" size="sm" />
Simulate a dropped connection on the next reply
</label>
</section>
</template>
<style scoped>
.chat {
display: flex;
flex-direction: column;
gap: var(--ghost-space-gap-sm);
block-size: 30rem;
max-inline-size: 40rem;
}
.chat__title {
border: 0;
font-size: var(--ghost-type-size-lg);
font-weight: var(--ghost-type-weight-semibold);
line-height: var(--ghost-type-line-tight);
margin: 0;
padding: 0;
}
/* The log takes the remaining height, so a growing composer shrinks it. */
.chat__log-frame {
display: flex;
flex: 1;
flex-direction: column;
min-block-size: 0;
position: relative;
}
.chat__log {
border: var(--ghost-border-hairline-width) solid var(--ghost-border-default);
border-radius: var(--ghost-radius-md);
flex: 1;
min-block-size: 0;
}
.chat__messages {
display: grid;
gap: var(--ghost-space-gap-md);
list-style: none;
margin: 0;
padding: var(--ghost-space-inset-sm);
}
.chat__messages > li {
margin: 0;
}
.chat__author {
color: var(--ghost-surface-fg);
font-weight: var(--ghost-type-weight-medium);
}
.chat__text {
white-space: pre-wrap;
}
.chat__jump {
inline-size: fit-content;
inset-block-end: var(--ghost-space-inset-sm);
inset-inline: 0;
margin-inline: auto;
position: absolute;
}
.chat__composer {
align-items: end;
display: grid;
gap: var(--ghost-space-gap-xs) var(--ghost-space-gap-sm);
grid-template-columns: minmax(0, 1fr) auto;
margin: 0;
}
.chat__hint {
color: var(--ghost-text-muted);
font-size: var(--ghost-type-size-sm);
grid-column: 1 / -1;
margin: 0;
}
.chat__option {
align-items: center;
display: inline-flex;
font-size: var(--ghost-type-size-sm);
gap: var(--ghost-space-gap-xs);
}
</style>
Type a message and press Enter. The assistant's reply arrives as a typing indicator, then streams in word by word, and the log follows it. Scroll up while it streams: the log stops following and Jump to latest appears with a count of replies that finished while you were away. Check Simulate a dropped connection to see a failed reply.
The example puts the pieces together like this:
- Log. A themed
GhostScrollAreawithstick-to-bottom, alabel, andv-model:stuck="following"wraps an<ol role="list">with one<li>per message, keyed by message id. The explicitrole="list"keeps list semantics in WebKit after the bullets are removed. The log is a flex child withmin-block-size: 0; flex: 1, so the composer growing shrinks the log instead of the page. - Messages.
side="end"for the current user,statusfor arrival, andtyping-labelwith the author's name. The reply is one message that goestyping → streaming → completeon the same component instance, so it keeps its place and DOM identity. - Jump to latest. A button shown while
followingisfalse. Clicking it setsfollowingtotrue, which scrolls to the bottom instantly. When it was activated from the keyboard (the button matches:focus-visible), focus moves to the composer first; a click or tap leaves focus alone so a phone's keyboard does not open. - Composer. A
<form>with aGhostTextarea(submit-on-enter,auto-resize,max-rows,readonlywhile sending,enterkeyhint="send") and a visible key hint wired througharia-describedby. The form'ssubmithandler ignores an empty draft. - Announcements. One status region, described below.
Sides
Messages from another person on the start side and from the current user on the end side, each named by its header.
- ALAda LovelaceCan you review the release notes before the 2 PM cut?
- YOYouOn it. I will leave comments in the draft by 1:30.
<script setup lang="ts">
import { GhostAvatar, GhostChatMessage } from '@ghostvue/themes'
const messages = [
{
id: 1,
author: 'Ada Lovelace',
mine: false,
at: '2026-03-02T10:42:00Z',
time: '10:42',
text: 'Can you review the release notes before the 2 PM cut?',
},
{
id: 2,
author: 'You',
mine: true,
at: '2026-03-02T10:44:00Z',
time: '10:44',
text: 'On it. I will leave comments in the draft by 1:30.',
},
] as const
</script>
<template>
<ol class="chat-sides" role="list">
<li v-for="message in messages" :key="message.id">
<GhostChatMessage :side="message.mine ? 'end' : 'start'">
<template #avatar>
<GhostAvatar :name="message.author" size="sm" aria-hidden="true" />
</template>
<template #header>
<span class="chat-sides__author">{{ message.author }}</span>
<time :datetime="message.at">{{ message.time }}</time>
</template>
{{ message.text }}
</GhostChatMessage>
</li>
</ol>
</template>
<style scoped>
.chat-sides {
display: grid;
gap: var(--ghost-space-gap-md);
list-style: none;
margin: 0;
max-inline-size: 36rem;
padding: 0;
}
.chat-sides > li {
margin: 0;
}
.chat-sides__author {
color: var(--ghost-surface-fg);
font-weight: var(--ghost-type-weight-medium);
}
</style>
side is start (the default) or end. It is logical: in a right-to-left layout end sits on the left. It only changes data-side and the themed layout, never the DOM order or reading order. Conventionally end is the current user. The themed recipe colors start bubbles with the muted surface and end bubbles with the primary action colors; links in an end bubble use the text color and stay underlined.
Typing and streaming
A reply that has not arrived yet, with animated dots and a visually hidden typing label.
- YouIs the staging deploy finished?
- GHGrace HopperGrace Hopper is typing
<script setup lang="ts">
import { GhostAvatar, GhostChatMessage } from '@ghostvue/themes'
</script>
<template>
<ol class="chat-typing" role="list">
<li>
<GhostChatMessage side="end">
<template #header>
<span class="chat-typing__author">You</span>
<time datetime="2026-03-02T10:44:00Z">10:44</time>
</template>
Is the staging deploy finished?
</GhostChatMessage>
</li>
<li>
<!-- The same instance later switches to streaming, then complete. -->
<GhostChatMessage status="typing" typing-label="Grace Hopper is typing">
<template #avatar>
<GhostAvatar name="Grace Hopper" size="sm" aria-hidden="true" />
</template>
<template #header>
<span class="chat-typing__author">Grace Hopper</span>
</template>
</GhostChatMessage>
</li>
</ol>
</template>
<style scoped>
.chat-typing {
display: grid;
gap: var(--ghost-space-gap-md);
list-style: none;
margin: 0;
max-inline-size: 36rem;
padding: 0;
}
.chat-typing > li {
margin: 0;
}
.chat-typing__author {
color: var(--ghost-surface-fg);
font-weight: var(--ghost-type-weight-medium);
}
</style>
status describes arrival only:
status | Bubble shows |
|---|---|
complete | The default slot. The default status. |
typing | Three dots and the visually hidden label. |
streaming | The default slot as it grows, chunk by chunk. |
The dots are hidden from assistive technology; a screen reader reads typingLabel instead ("Grace Hopper is typing"). The themed dots pulse, and are static under prefers-reduced-motion: reduce. The component never changes status on its own and never times out; when a stream stops, set complete and show the error in the footer slot. Delivery state (sent, failed, read) is your data and also goes in the footer.
Slots
| Slot | Part | Use for |
|---|---|---|
avatar | avatar | A GhostAvatar. Add aria-hidden="true" when the header names the author. |
header | header | Author and <time datetime>. Names the message. |
default | bubble | Message content. Not rendered while status is typing. |
footer | footer | Delivery state, errors (GhostInlineAlert), and actions such as Copy, Retry. |
Each part is rendered only when its slot is provided, except bubble, which is always there. Message text is rendered by your slot markup, so Vue escapes it; if you render HTML from a model with v-html, sanitize it yourself.
Accessibility
- One article per message. The root is an
<article>. With aheaderslot it is named by the header (aria-labelledby), so screen-reader article navigation reads "Ada, 10:42" for each message. A consumeraria-labeloraria-labelledbyreplaces that name. Without a header the article has no name, which is valid. - No
aria-busy. Some screen readers leave busy content out of browse mode, which would hide the typing label and the partial reply. - Not a live region. Do not put
role="log"oraria-liveon the log: it would read a streamed reply as a burst of fragments. Use one status region. - Focus. The message is not focusable and adds no key handlers. Links and buttons in slots keep their own tab order.
GhostScrollAreanever scrolls a keyboard-focused control in an earlier message out of view.
Announcements
Render one <GhostVisuallyHidden role="status" aria-atomic="true"> outside the log. role="status" is polite, so announcements wait for current speech and never move focus. Write each announcement as a fresh change: clear the region, set the text on a later tick, and clear it again after a few seconds. Then two identical announcements in a row are both spoken, and browse mode does not find a stale copy after the log.
| When | Announce |
|---|---|
| Someone else's message arrives complete | Author and full text ("Ada: The standup…") |
| Someone else's reply starts typing/streaming | Once: "Assistant is replying" |
| A streamed reply completes | Author and the start of the text, not all of it |
| A send or stream fails | Once: "Reply failed", instead of the arrival |
| Your own message, each streamed chunk | Nothing |
Announcements happen whether or not the log is following, so a reader who has scrolled up still hears new replies.
Advanced: headless composition
For teams that bring their own design system, the headless GhostChatMessage from @ghostvue/vue renders the same article and parts with no styles. useGhostChatMessage({ side, status, hasHeader }) returns rootProps, avatarProps, headerProps (with the generated header id), bubbleProps, footerProps, and typingProps so a fully custom template can reproduce the same structure.
Styling hooks
Parts are direct children of the root in the order avatar, header, bubble, footer, so place them with grid areas on the root; there are no wrapper elements. Hooks:
- class
ghost-chat-messageon the root data-part="root" | "avatar" | "header" | "bubble" | "footer" | "typing" | "typing-dot"data-side="start" | "end"anddata-status="complete" | "typing" | "streaming"on the root
.ghost-chat-message[data-side='end'] > [data-part='bubble'] {
background: var(--brand-bubble-bg);
}API
| Prop | Type | Default | Description |
|---|---|---|---|
side | GhostChatMessageSide | "start" | Which inline side the message sits on. Never changes DOM or reading order, only data-side and the themed layout. |
status | GhostChatMessageStatus | "complete" | Arrival state. typing renders the typing indicator instead of the default slot. The component never sets aria-busy. |
typingLabel | string | "Typing" | Visually hidden text read in place of the typing dots while status is typing. Localize it, usually with the author ("Ada is typing"). |
| Slot | Slot props | Description |
|---|---|---|
avatar | — | Avatar part, usually a GhostAvatar. Mark it aria-hidden when the header names the author. |
default | — | Bubble content. Not rendered while status is typing. |
footer | — | Footer part for delivery state, errors, actions, and reactions. |
header | — | Header part with author and time. Becomes the article's accessible name. |
@ghostvue/themes adds no props, events, or slots to the headless GhostChatMessage API, which it forwards.
See the GhostChatMessage specification for the complete behavior and compatibility contract.