Chat Message
Message in an AI conversation. User bubbles on the right, assistant replies with an avatar, hover actions, a typing indicator, and optional token streaming.
Can you draft an invoice in Rupiah for a website project?
Markas AI
Sure. Here is a simple layout for it:
Design and build, Rp 12.500.000
VAT 11%, Rp 1.375.000
Total due, Rp 13.875.000
Add a 14 day payment term, please.
Markas AI
Typing
Can you draft an invoice in Rupiah for a website project?
Markas AI
Sure. Here is a simple layout for it:
Design and build, Rp 12.500.000
VAT 11%, Rp 1.375.000
Total due, Rp 13.875.000
Add a 14 day payment term, please.
Markas AI
Typing
Can you draft an invoice in Rupiah for a website project?
Markas AI
Sure. Here is a simple layout for it:
Design and build, Rp 12.500.000
VAT 11%, Rp 1.375.000
Total due, Rp 13.875.000
Add a 14 day payment term, please.
Markas AI
Typing
Can you draft an invoice in Rupiah for a website project?
Markas AI
Sure. Here is a simple layout for it:
Design and build, Rp 12.500.000
VAT 11%, Rp 1.375.000
Total due, Rp 13.875.000
Add a 14 day payment term, please.
Markas AI
Typing
Can you draft an invoice in Rupiah for a website project?
Markas AI
Sure. Here is a simple layout for it:
Design and build, Rp 12.500.000
VAT 11%, Rp 1.375.000
Total due, Rp 13.875.000
Add a 14 day payment term, please.
Markas AI
Typing
@php
$log = 'grid gap-4';
$answer = "Sure. Here is a simple layout for it:\nDesign and build, Rp 12.500.000\nVAT 11%, Rp 1.375.000\nTotal due, Rp 13.875.000";
@endphp
<div role="log" aria-label="Conversation" class="{{ $log }}">
<x-markas.chat-message from="user" text="Can you draft an invoice in Rupiah for a website project?" time="10:24" />
<x-markas.chat-message :text="$answer" time="10:24" assistant-label="Markas AI" />
<x-markas.chat-message from="user" text="Add a 14 day payment term, please." time="10:25" />
<x-markas.chat-message typing assistant-label="Markas AI" />
</div>import { ChatMessage } from "@/components/markas/ChatMessage";
const log = "grid gap-4";
const answer =
"Sure. Here is a simple layout for it:\nDesign and build, Rp 12.500.000\nVAT 11%, Rp 1.375.000\nTotal due, Rp 13.875.000";
export default function ChatMessageExample() {
return (
<div role="log" aria-label="Conversation" className={log}>
<ChatMessage
from="user"
text="Can you draft an invoice in Rupiah for a website project?"
time="10:24"
/>
<ChatMessage text={answer} time="10:24" assistantLabel="Markas AI" />
<ChatMessage
from="user"
text="Add a 14 day payment term, please."
time="10:25"
/>
<ChatMessage typing assistantLabel="Markas AI" />
</div>
);
}<script setup lang="ts">
import ChatMessage from "@/components/markas/ChatMessage.vue";
const log = "grid gap-4";
const answer =
"Sure. Here is a simple layout for it:\nDesign and build, Rp 12.500.000\nVAT 11%, Rp 1.375.000\nTotal due, Rp 13.875.000";
</script>
<template>
<div role="log" aria-label="Conversation" :class="log">
<ChatMessage
from="user"
text="Can you draft an invoice in Rupiah for a website project?"
time="10:24"
/>
<ChatMessage :text="answer" time="10:24" assistant-label="Markas AI" />
<ChatMessage
from="user"
text="Add a 14 day payment term, please."
time="10:25"
/>
<ChatMessage typing assistant-label="Markas AI" />
</div>
</template><script lang="ts">
import ChatMessage from "$lib/components/markas/ChatMessage.svelte";
const log = "grid gap-4";
const answer =
"Sure. Here is a simple layout for it:\nDesign and build, Rp 12.500.000\nVAT 11%, Rp 1.375.000\nTotal due, Rp 13.875.000";
</script>
<div role="log" aria-label="Conversation" class={log}>
<ChatMessage
from="user"
text="Can you draft an invoice in Rupiah for a website project?"
time="10:24"
/>
<ChatMessage text={answer} time="10:24" assistantLabel="Markas AI" />
<ChatMessage
from="user"
text="Add a 14 day payment term, please."
time="10:25"
/>
<ChatMessage typing assistantLabel="Markas AI" />
</div>---
import ChatMessage from "@/components/markas/ChatMessage.astro";
const log = "grid gap-4";
const answer =
"Sure. Here is a simple layout for it:\nDesign and build, Rp 12.500.000\nVAT 11%, Rp 1.375.000\nTotal due, Rp 13.875.000";
---
<div role="log" aria-label="Conversation" class={log}>
<ChatMessage
from="user"
text="Can you draft an invoice in Rupiah for a website project?"
time="10:24"
/>
<ChatMessage text={answer} time="10:24" assistantLabel="Markas AI" />
<ChatMessage
from="user"
text="Add a 14 day payment term, please."
time="10:25"
/>
<ChatMessage typing assistantLabel="Markas AI" />
</div>import { Component } from "@angular/core";
import { ChatMessage } from "./markas/chat-message.component";
@Component({
selector: "markas-example",
imports: [ChatMessage],
template: `
<div role="log" aria-label="Conversation" [class]="log">
<markas-chat-message
from="user"
text="Can you draft an invoice in Rupiah for a website project?"
time="10:24"
/>
<markas-chat-message
[text]="answer"
time="10:24"
assistantLabel="Markas AI"
/>
<markas-chat-message
from="user"
text="Add a 14 day payment term, please."
time="10:25"
/>
<markas-chat-message typing assistantLabel="Markas AI" />
</div>
`,
})
export default class ChatMessageExample {
protected readonly log = "grid gap-4";
protected readonly answer =
"Sure. Here is a simple layout for it:\nDesign and build, Rp 12.500.000\nVAT 11%, Rp 1.375.000\nTotal due, Rp 13.875.000";
}Examples
Support chat with bubbles
My invoice shows Rp 0 for shipping. Is that right?
Support bot
Yes. Orders above Rp 500.000 ship for free, so the shipping line stays at Rp 0.
My invoice shows Rp 0 for shipping. Is that right?
Support bot
Yes. Orders above Rp 500.000 ship for free, so the shipping line stays at Rp 0.
My invoice shows Rp 0 for shipping. Is that right?
Support bot
Yes. Orders above Rp 500.000 ship for free, so the shipping line stays at Rp 0.
My invoice shows Rp 0 for shipping. Is that right?
Support bot
Yes. Orders above Rp 500.000 ship for free, so the shipping line stays at Rp 0.
My invoice shows Rp 0 for shipping. Is that right?
Support bot
Yes. Orders above Rp 500.000 ship for free, so the shipping line stays at Rp 0.
@php
$log = 'grid gap-4 rounded-xl border border-line bg-surface p-4';
@endphp
<div role="log" aria-label="Support chat" class="{{ $log }}">
<x-markas.chat-message from="user" text="My invoice shows Rp 0 for shipping. Is that right?" time="14:02" />
<x-markas.chat-message
variant="bubble"
text="Yes. Orders above Rp 500.000 ship for free, so the shipping line stays at Rp 0."
time="14:02"
assistant-label="Support bot"
/>
</div>import { ChatMessage } from "@/components/markas/ChatMessage";
const log = "grid gap-4 rounded-xl border border-line bg-surface p-4";
export default function Example() {
return (
<div role="log" aria-label="Support chat" className={log}>
<ChatMessage
from="user"
text="My invoice shows Rp 0 for shipping. Is that right?"
time="14:02"
/>
<ChatMessage
variant="bubble"
text="Yes. Orders above Rp 500.000 ship for free, so the shipping line stays at Rp 0."
time="14:02"
assistantLabel="Support bot"
/>
</div>
);
}<script setup lang="ts">
import ChatMessage from "@/components/markas/ChatMessage.vue";
const log = "grid gap-4 rounded-xl border border-line bg-surface p-4";
</script>
<template>
<div role="log" aria-label="Support chat" :class="log">
<ChatMessage
from="user"
text="My invoice shows Rp 0 for shipping. Is that right?"
time="14:02"
/>
<ChatMessage
variant="bubble"
text="Yes. Orders above Rp 500.000 ship for free, so the shipping line stays at Rp 0."
time="14:02"
assistant-label="Support bot"
/>
</div>
</template><script lang="ts">
import ChatMessage from "$lib/components/markas/ChatMessage.svelte";
const log = "grid gap-4 rounded-xl border border-line bg-surface p-4";
</script>
<div role="log" aria-label="Support chat" class={log}>
<ChatMessage
from="user"
text="My invoice shows Rp 0 for shipping. Is that right?"
time="14:02"
/>
<ChatMessage
variant="bubble"
text="Yes. Orders above Rp 500.000 ship for free, so the shipping line stays at Rp 0."
time="14:02"
assistantLabel="Support bot"
/>
</div>---
import ChatMessage from "@/components/markas/ChatMessage.astro";
const log = "grid gap-4 rounded-xl border border-line bg-surface p-4";
---
<div role="log" aria-label="Support chat" class={log}>
<ChatMessage
from="user"
text="My invoice shows Rp 0 for shipping. Is that right?"
time="14:02"
/>
<ChatMessage
variant="bubble"
text="Yes. Orders above Rp 500.000 ship for free, so the shipping line stays at Rp 0."
time="14:02"
assistantLabel="Support bot"
/>
</div>import { Component } from "@angular/core";
import { ChatMessage } from "./markas/chat-message.component";
@Component({
selector: "markas-example",
imports: [ChatMessage],
template: `
<div role="log" aria-label="Support chat" [class]="log">
<markas-chat-message
from="user"
text="My invoice shows Rp 0 for shipping. Is that right?"
time="14:02"
/>
<markas-chat-message
variant="bubble"
text="Yes. Orders above Rp 500.000 ship for free, so the shipping line stays at Rp 0."
time="14:02"
assistantLabel="Support bot"
/>
</div>
`,
})
export default class ChatMessageBubbleExample {
protected readonly log =
"grid gap-4 rounded-xl border border-line bg-surface p-4";
}Streaming answer
When is VAT due for my October invoices?
Markas AI
VAT for October is due by the end of November. Report it in your monthly return and pay before you file, so the payment code is already on record.VAT for October is due by the end of November. Report it in your monthly return and pay before you file, so the payment code is already on record.
When is VAT due for my October invoices?
Markas AI
VAT for October is due by the end of November. Report it in your monthly return and pay before you file, so the payment code is already on record.VAT for October is due by the end of November. Report it in your monthly return and pay before you file, so the payment code is already on record.
When is VAT due for my October invoices?
Markas AI
VAT for October is due by the end of November. Report it in your monthly return and pay before you file, so the payment code is already on record.VAT for October is due by the end of November. Report it in your monthly return and pay before you file, so the payment code is already on record.
When is VAT due for my October invoices?
Markas AI
VAT for October is due by the end of November. Report it in your monthly return and pay before you file, so the payment code is already on record.VAT for October is due by the end of November. Report it in your monthly return and pay before you file, so the payment code is already on record.
When is VAT due for my October invoices?
Markas AI
VAT for October is due by the end of November. Report it in your monthly return and pay before you file, so the payment code is already on record.VAT for October is due by the end of November. Report it in your monthly return and pay before you file, so the payment code is already on record.
@php
$log = 'grid gap-4';
@endphp
<div role="log" aria-label="Conversation" class="{{ $log }}">
<x-markas.chat-message from="user" text="When is VAT due for my October invoices?" time="09:12" />
<x-markas.chat-message
stream
text="VAT for October is due by the end of November. Report it in your monthly return and pay before you file, so the payment code is already on record."
time="09:12"
assistant-label="Markas AI"
/>
</div>import { ChatMessage } from "@/components/markas/ChatMessage";
const log = "grid gap-4";
export default function Example() {
return (
<div role="log" aria-label="Conversation" className={log}>
<ChatMessage
from="user"
text="When is VAT due for my October invoices?"
time="09:12"
/>
<ChatMessage
stream
text="VAT for October is due by the end of November. Report it in your monthly return and pay before you file, so the payment code is already on record."
time="09:12"
assistantLabel="Markas AI"
/>
</div>
);
}<script setup lang="ts">
import ChatMessage from "@/components/markas/ChatMessage.vue";
const log = "grid gap-4";
</script>
<template>
<div role="log" aria-label="Conversation" :class="log">
<ChatMessage
from="user"
text="When is VAT due for my October invoices?"
time="09:12"
/>
<ChatMessage
stream
text="VAT for October is due by the end of November. Report it in your monthly return and pay before you file, so the payment code is already on record."
time="09:12"
assistant-label="Markas AI"
/>
</div>
</template><script lang="ts">
import ChatMessage from "$lib/components/markas/ChatMessage.svelte";
const log = "grid gap-4";
</script>
<div role="log" aria-label="Conversation" class={log}>
<ChatMessage
from="user"
text="When is VAT due for my October invoices?"
time="09:12"
/>
<ChatMessage
stream
text="VAT for October is due by the end of November. Report it in your monthly return and pay before you file, so the payment code is already on record."
time="09:12"
assistantLabel="Markas AI"
/>
</div>---
import ChatMessage from "@/components/markas/ChatMessage.astro";
const log = "grid gap-4";
---
<div role="log" aria-label="Conversation" class={log}>
<ChatMessage
from="user"
text="When is VAT due for my October invoices?"
time="09:12"
/>
<ChatMessage
stream
text="VAT for October is due by the end of November. Report it in your monthly return and pay before you file, so the payment code is already on record."
time="09:12"
assistantLabel="Markas AI"
/>
</div>import { Component } from "@angular/core";
import { ChatMessage } from "./markas/chat-message.component";
@Component({
selector: "markas-example",
imports: [ChatMessage],
template: `
<div role="log" aria-label="Conversation" [class]="log">
<markas-chat-message
from="user"
text="When is VAT due for my October invoices?"
time="09:12"
/>
<markas-chat-message
stream
text="VAT for October is due by the end of November. Report it in your monthly return and pay before you file, so the payment code is already on record."
time="09:12"
assistantLabel="Markas AI"
/>
</div>
`,
})
export default class ChatMessageStreamingExample {
protected readonly log = "grid gap-4";
}Read-only transcript
Please resend invoice INV-2041.
Markas AI
Done. A fresh copy went to finance@sinarjaya.co.id.
Thanks, received it.
Please resend invoice INV-2041.
Markas AI
Done. A fresh copy went to finance@sinarjaya.co.id.
Thanks, received it.
Please resend invoice INV-2041.
Markas AI
Done. A fresh copy went to finance@sinarjaya.co.id.
Thanks, received it.
Please resend invoice INV-2041.
Markas AI
Done. A fresh copy went to finance@sinarjaya.co.id.
Thanks, received it.
Please resend invoice INV-2041.
Markas AI
Done. A fresh copy went to finance@sinarjaya.co.id.
Thanks, received it.
@php
$log = 'grid gap-3';
@endphp
<div role="log" aria-label="Chat transcript" class="{{ $log }}">
<x-markas.chat-message from="user" :actions="false" text="Please resend invoice INV-2041." time="Mon 08:40" />
<x-markas.chat-message
:actions="false"
variant="bubble"
text="Done. A fresh copy went to finance@sinarjaya.co.id."
time="Mon 08:40"
assistant-label="Markas AI"
/>
<x-markas.chat-message from="user" :actions="false" text="Thanks, received it." time="Mon 08:43" />
</div>import { ChatMessage } from "@/components/markas/ChatMessage";
const log = "grid gap-3";
export default function Example() {
return (
<div role="log" aria-label="Chat transcript" className={log}>
<ChatMessage
from="user"
actions={false}
text="Please resend invoice INV-2041."
time="Mon 08:40"
/>
<ChatMessage
actions={false}
variant="bubble"
text="Done. A fresh copy went to finance@sinarjaya.co.id."
time="Mon 08:40"
assistantLabel="Markas AI"
/>
<ChatMessage
from="user"
actions={false}
text="Thanks, received it."
time="Mon 08:43"
/>
</div>
);
}<script setup lang="ts">
import ChatMessage from "@/components/markas/ChatMessage.vue";
const log = "grid gap-3";
</script>
<template>
<div role="log" aria-label="Chat transcript" :class="log">
<ChatMessage
from="user"
:actions="false"
text="Please resend invoice INV-2041."
time="Mon 08:40"
/>
<ChatMessage
:actions="false"
variant="bubble"
text="Done. A fresh copy went to finance@sinarjaya.co.id."
time="Mon 08:40"
assistant-label="Markas AI"
/>
<ChatMessage
from="user"
:actions="false"
text="Thanks, received it."
time="Mon 08:43"
/>
</div>
</template><script lang="ts">
import ChatMessage from "$lib/components/markas/ChatMessage.svelte";
const log = "grid gap-3";
</script>
<div role="log" aria-label="Chat transcript" class={log}>
<ChatMessage
from="user"
actions={false}
text="Please resend invoice INV-2041."
time="Mon 08:40"
/>
<ChatMessage
actions={false}
variant="bubble"
text="Done. A fresh copy went to finance@sinarjaya.co.id."
time="Mon 08:40"
assistantLabel="Markas AI"
/>
<ChatMessage
from="user"
actions={false}
text="Thanks, received it."
time="Mon 08:43"
/>
</div>---
import ChatMessage from "@/components/markas/ChatMessage.astro";
const log = "grid gap-3";
---
<div role="log" aria-label="Chat transcript" class={log}>
<ChatMessage
from="user"
actions={false}
text="Please resend invoice INV-2041."
time="Mon 08:40"
/>
<ChatMessage
actions={false}
variant="bubble"
text="Done. A fresh copy went to finance@sinarjaya.co.id."
time="Mon 08:40"
assistantLabel="Markas AI"
/>
<ChatMessage
from="user"
actions={false}
text="Thanks, received it."
time="Mon 08:43"
/>
</div>import { Component } from "@angular/core";
import { ChatMessage } from "./markas/chat-message.component";
@Component({
selector: "markas-example",
imports: [ChatMessage],
template: `
<div role="log" aria-label="Chat transcript" [class]="log">
<markas-chat-message
from="user"
[actions]="false"
text="Please resend invoice INV-2041."
time="Mon 08:40"
/>
<markas-chat-message
[actions]="false"
variant="bubble"
text="Done. A fresh copy went to finance@sinarjaya.co.id."
time="Mon 08:40"
assistantLabel="Markas AI"
/>
<markas-chat-message
from="user"
[actions]="false"
text="Thanks, received it."
time="Mon 08:43"
/>
</div>
`,
})
export default class ChatMessageTranscriptExample {
protected readonly log = "grid gap-3";
}Installation
npx markasui@latest add chat-messagepnpm dlx markasui@latest add chat-messageyarn dlx markasui@latest add chat-messagebunx --bun markasui@latest add chat-message- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Install the dependency:
npm install alpinejs - Copy the component source below to
resources/views/components/markas/chat-message.blade.php.
resources/views/components/markas/chat-message.blade.php
@props([
'from' => 'assistant',
'text' => '',
'variant' => 'plain',
'time' => null,
'avatar' => null,
'typing' => false,
'stream' => false,
'streamSpeed' => 40,
'actions' => true,
'userLabel' => 'You',
'assistantLabel' => 'Assistant',
'typingLabel' => 'Typing',
'actionsLabel' => 'Message actions',
'copyLabel' => 'Copy',
'copiedLabel' => 'Copied',
'likeLabel' => 'Good response',
'dislikeLabel' => 'Bad response',
'regenerateLabel' => 'Regenerate',
])
@php
$roots = [
'user' => 'group/message flex flex-col items-end gap-1',
'assistant' => 'group/message flex items-start gap-3',
];
$avatarClass = 'grid size-8 shrink-0 place-items-center overflow-hidden rounded-full border border-line bg-surface text-ink';
$avatarImage = 'size-full object-cover';
$avatarIcon = 'size-4';
$bodies = [
'user' => 'flex w-full flex-col items-end gap-1',
'assistant' => 'grid min-w-0 flex-1 justify-items-start gap-1',
];
$header = 'flex items-baseline gap-2 text-sm font-medium text-ink';
$contents = [
'user' => 'max-w-[85%] rounded-2xl rounded-br-md bg-primary px-4 py-2.5 text-sm leading-6 break-words whitespace-pre-line text-on-primary',
'plain' => 'text-sm leading-6 break-words whitespace-pre-line text-ink',
'bubble' => 'rounded-2xl rounded-tl-md bg-subtle px-4 py-2.5 text-sm leading-6 break-words whitespace-pre-line text-ink',
];
$timeClass = 'text-xs font-normal text-muted';
$footer = 'flex min-h-7 items-center gap-1';
$actionsClass = 'flex items-center gap-0.5 opacity-0 transition-opacity duration-150 ease-out group-focus-within/message:opacity-100 group-hover/message:opacity-100 motion-reduce:transition-none [@media(hover:none)]:opacity-100';
$action = 'group/action grid size-7 place-items-center rounded-md text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary aria-pressed:text-ink motion-reduce:transition-none';
$actionIcon = 'col-start-1 row-start-1 size-4';
$pressIcon = 'size-4 group-aria-pressed/action:fill-current/20';
$copyIcon = 'col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]/action:scale-50 group-data-[state=copied]/action:opacity-0 motion-reduce:transition-none';
$checkIcon = 'col-start-1 row-start-1 size-4 scale-50 opacity-0 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]/action:scale-100 group-data-[state=copied]/action:opacity-100 motion-reduce:transition-none';
$dots = 'inline-flex h-6 items-center gap-1';
$dot = [
'size-1.5 animate-pulse rounded-full bg-muted motion-reduce:animate-none',
'size-1.5 animate-pulse rounded-full bg-muted [animation-delay:150ms] motion-reduce:animate-none',
'size-1.5 animate-pulse rounded-full bg-muted [animation-delay:300ms] motion-reduce:animate-none',
];
$caret = 'ml-0.5 inline-block h-4 w-1.5 translate-y-0.5 animate-pulse rounded-xs bg-current motion-reduce:animate-none';
$srOnly = 'sr-only';
$paths = [
'spark' => 'M12 3c.4 4.6 2.4 6.6 7 7-4.6.4-6.6 2.4-7 7-.4-4.6-2.4-6.6-7-7 4.6-.4 6.6-2.4 7-7zM19 16c.2 1.6.9 2.3 2.5 2.5-1.6.2-2.3.9-2.5 2.5-.2-1.6-.9-2.3-2.5-2.5 1.6-.2 2.3-.9 2.5-2.5z',
'copy' => 'M9 9h10a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H11a2 2 0 0 1-2-2zM5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1',
'check' => 'm4 12 5 5L20 6',
'like' => 'M7 10v11M15 5.9 14 10h5.8a2 2 0 0 1 1.9 2.6l-2.3 8a2 2 0 0 1-1.9 1.4H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.8a2 2 0 0 0 1.8-1.1L12 2a3.1 3.1 0 0 1 3 3.9z',
'dislike' => 'M17 14V3M9 18.1 10 14H4.2a2 2 0 0 1-1.9-2.6l2.3-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.8a2 2 0 0 0-1.8 1.1L12 22a3.1 3.1 0 0 1-3-3.9z',
'regenerate' => 'M3 12a9 9 0 0 1 15.7-6L21 8M21 3v5h-5M21 12a9 9 0 0 1-15.7 6L3 16M8 16H3v5',
];
$svg = fn (string $path, string $class) => '<svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="'.$class.'"><path d="'.$paths[$path].'" /></svg>';
$assistant = $from === 'assistant';
$content = $assistant ? $contents[$variant] : $contents['user'];
@endphp
{{-- Streaming reveals the text one token at a time (off with reduced motion). Like, dislike, and regenerate dispatch feedback and regenerate events. --}}
<article
x-data="{
text: @js((string) $text),
tokens: @js(preg_split('/(\s+)/', (string) $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY)),
shown: Infinity,
copied: false,
feedback: null,
timer: null,
get streaming() {
return @js((bool) $stream) && this.shown < this.tokens.length;
},
init() {
if (! @js((bool) $stream) || matchMedia('(prefers-reduced-motion: reduce)').matches) return;
this.shown = 0;
const tick = () => {
if (! this.streaming) return;
this.shown++;
this.timer = setTimeout(tick, {{ (int) $streamSpeed }});
};
this.timer = setTimeout(tick, {{ (int) $streamSpeed }});
},
async copy() {
try {
await navigator.clipboard.writeText(this.text);
} catch {
return;
}
this.copied = true;
clearTimeout(this.timer);
this.timer = setTimeout(() => (this.copied = false), 2000);
},
rate(value) {
this.feedback = this.feedback === value ? null : value;
this.$dispatch('feedback', this.feedback);
},
destroy() {
clearTimeout(this.timer);
},
}"
data-from="{{ $from }}"
aria-label="{{ $assistant ? $assistantLabel : $userLabel }}"
{{ $attributes->class([$roots[$from]]) }}
>
@if ($assistant)
<span aria-hidden="true" class="{{ $avatarClass }}">
@if ($avatar)
<img src="{{ $avatar }}" alt="" class="{{ $avatarImage }}" />
@else
{!! $svg('spark', $avatarIcon) !!}
@endif
</span>
@endif
<div class="{{ $bodies[$from] }}">
@if ($assistant)
<p class="{{ $header }}">{{ $assistantLabel }}@if ($time)<time class="{{ $timeClass }}">{{ $time }}</time>@endif</p>
@endif
<div class="{{ $content }}">@if ($typing)<span role="status" class="{{ $dots }}"><span class="{{ $srOnly }}">{{ $typingLabel }}</span>@foreach ($dot as $dotClass)<span aria-hidden="true" class="{{ $dotClass }}"></span>@endforeach</span>@elseif ($stream)<span class="{{ $srOnly }}">{{ $text }}</span><span aria-hidden="true" x-text="tokens.slice(0, shown).join('')">{{ $text }}</span><template x-if="streaming"><span aria-hidden="true" class="{{ $caret }}"></span></template>@else{{ $text }}@endif</div>
<div class="{{ $footer }}">
@if ($actions && ! $typing)
<div x-show="! streaming" role="group" aria-label="{{ $actionsLabel }}" class="{{ $actionsClass }}">
<button type="button" aria-label="{{ $copyLabel }}" data-state="idle" x-bind:data-state="copied ? 'copied' : 'idle'" x-on:click="copy()" class="{{ $action }}">
{!! $svg('copy', $copyIcon) !!}
{!! $svg('check', $checkIcon) !!}
</button>
@if ($assistant)
@foreach (['like' => $likeLabel, 'dislike' => $dislikeLabel] as $value => $label)
<button type="button" aria-label="{{ $label }}" aria-pressed="false" x-bind:aria-pressed="feedback === '{{ $value }}'" x-on:click="rate('{{ $value }}')" class="{{ $action }}">
{!! $svg($value, $pressIcon) !!}
</button>
@endforeach
<button type="button" aria-label="{{ $regenerateLabel }}" x-on:click="$dispatch('regenerate')" class="{{ $action }}">
{!! $svg('regenerate', $actionIcon) !!}
</button>
@endif
<span role="status" class="{{ $srOnly }}" x-text="copied ? @js($copiedLabel) : ''"></span>
</div>
@endif
@if (! $assistant && $time)
<time class="{{ $timeClass }}">{{ $time }}</time>
@endif
</div>
</div>
</article>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/components/markas/ChatMessage.tsx.
src/components/markas/ChatMessage.tsx
"use client";
import {
useEffect,
useLayoutEffect,
useRef,
useState,
type ComponentProps,
} from "react";
const roots = {
user: "group/message flex flex-col items-end gap-1",
assistant: "group/message flex items-start gap-3",
};
const avatar =
"grid size-8 shrink-0 place-items-center overflow-hidden rounded-full border border-line bg-surface text-ink";
const avatarImage = "size-full object-cover";
const avatarIcon = "size-4";
const bodies = {
user: "flex w-full flex-col items-end gap-1",
assistant: "grid min-w-0 flex-1 justify-items-start gap-1",
};
const header = "flex items-baseline gap-2 text-sm font-medium text-ink";
const contents = {
user: "max-w-[85%] rounded-2xl rounded-br-md bg-primary px-4 py-2.5 text-sm leading-6 break-words whitespace-pre-line text-on-primary",
plain: "text-sm leading-6 break-words whitespace-pre-line text-ink",
bubble:
"rounded-2xl rounded-tl-md bg-subtle px-4 py-2.5 text-sm leading-6 break-words whitespace-pre-line text-ink",
};
const time = "text-xs font-normal text-muted";
const footer = "flex min-h-7 items-center gap-1";
const actions =
"flex items-center gap-0.5 opacity-0 transition-opacity duration-150 ease-out group-focus-within/message:opacity-100 group-hover/message:opacity-100 motion-reduce:transition-none [@media(hover:none)]:opacity-100";
const action =
"group/action grid size-7 place-items-center rounded-md text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary aria-pressed:text-ink motion-reduce:transition-none";
const actionIcon = "col-start-1 row-start-1 size-4";
const pressIcon = "size-4 group-aria-pressed/action:fill-current/20";
const copyIcon =
"col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]/action:scale-50 group-data-[state=copied]/action:opacity-0 motion-reduce:transition-none";
const checkIcon =
"col-start-1 row-start-1 size-4 scale-50 opacity-0 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]/action:scale-100 group-data-[state=copied]/action:opacity-100 motion-reduce:transition-none";
const dots = "inline-flex h-6 items-center gap-1";
const dot = [
"size-1.5 animate-pulse rounded-full bg-muted motion-reduce:animate-none",
"size-1.5 animate-pulse rounded-full bg-muted [animation-delay:150ms] motion-reduce:animate-none",
"size-1.5 animate-pulse rounded-full bg-muted [animation-delay:300ms] motion-reduce:animate-none",
];
const caret =
"ml-0.5 inline-block h-4 w-1.5 translate-y-0.5 animate-pulse rounded-xs bg-current motion-reduce:animate-none";
const srOnly = "sr-only";
const PATHS = {
spark:
"M12 3c.4 4.6 2.4 6.6 7 7-4.6.4-6.6 2.4-7 7-.4-4.6-2.4-6.6-7-7 4.6-.4 6.6-2.4 7-7zM19 16c.2 1.6.9 2.3 2.5 2.5-1.6.2-2.3.9-2.5 2.5-.2-1.6-.9-2.3-2.5-2.5 1.6-.2 2.3-.9 2.5-2.5z",
copy: "M9 9h10a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H11a2 2 0 0 1-2-2zM5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1",
check: "m4 12 5 5L20 6",
like: "M7 10v11M15 5.9 14 10h5.8a2 2 0 0 1 1.9 2.6l-2.3 8a2 2 0 0 1-1.9 1.4H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.8a2 2 0 0 0 1.8-1.1L12 2a3.1 3.1 0 0 1 3 3.9z",
dislike:
"M17 14V3M9 18.1 10 14H4.2a2 2 0 0 1-1.9-2.6l2.3-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.8a2 2 0 0 0-1.8 1.1L12 22a3.1 3.1 0 0 1-3-3.9z",
regenerate:
"M3 12a9 9 0 0 1 15.7-6L21 8M21 3v5h-5M21 12a9 9 0 0 1-15.7 6L3 16M8 16H3v5",
};
/** How long the check mark stays after copying. */
const COPIED_MS = 2000;
const cx = (...c: (string | false | null | undefined)[]) =>
c.filter(Boolean).join(" ");
const reducedMotion = () =>
typeof matchMedia === "function" &&
matchMedia("(prefers-reduced-motion: reduce)").matches;
/** Words and the spaces between them, so streaming reveals one token at a time. */
const tokenize = (text: string) => text.split(/(\s+)/).filter(Boolean);
const useClientLayoutEffect =
typeof window === "undefined" ? useEffect : useLayoutEffect;
const Icon = ({ d, className }: { d: string; className: string }) => (
<svg
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
className={className}
>
<path d={d} />
</svg>
);
export type ChatMessageFeedback = "like" | "dislike" | null;
export type ChatMessageProps = ComponentProps<"article"> & {
from?: "user" | "assistant";
text?: string;
/** Assistant messages: plain text or a soft bubble. */
variant?: "plain" | "bubble";
time?: string;
/** Image URL for the assistant avatar. Defaults to a spark icon. */
avatar?: string;
/** Shows three dots instead of the text. */
typing?: boolean;
/** Reveals the text token by token with a caret. Off with reduced motion. */
stream?: boolean;
/** Pause between streamed tokens, in ms. */
streamSpeed?: number;
/** Shows copy, and for the assistant like, dislike, and regenerate. */
actions?: boolean;
onFeedback?: (value: ChatMessageFeedback) => void;
onRegenerate?: () => void;
userLabel?: string;
assistantLabel?: string;
typingLabel?: string;
actionsLabel?: string;
copyLabel?: string;
copiedLabel?: string;
likeLabel?: string;
dislikeLabel?: string;
regenerateLabel?: string;
};
export function ChatMessage({
from = "assistant",
text = "",
variant = "plain",
time: timeText,
avatar: avatarSrc,
typing = false,
stream = false,
streamSpeed = 40,
actions: showActions = true,
onFeedback,
onRegenerate,
userLabel = "You",
assistantLabel = "Assistant",
typingLabel = "Typing",
actionsLabel = "Message actions",
copyLabel = "Copy",
copiedLabel = "Copied",
likeLabel = "Good response",
dislikeLabel = "Bad response",
regenerateLabel = "Regenerate",
className,
...props
}: ChatMessageProps) {
const assistant = from === "assistant";
const tokens = tokenize(text);
const [shown, setShown] = useState(Infinity);
const [copied, setCopied] = useState(false);
const [feedback, setFeedback] = useState<ChatMessageFeedback>(null);
const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
const streaming = stream && shown < tokens.length;
useClientLayoutEffect(() => {
if (stream && !reducedMotion()) setShown(0);
}, [stream]);
useEffect(() => {
if (!streaming) return;
const next = setTimeout(() => setShown((count) => count + 1), streamSpeed);
return () => clearTimeout(next);
}, [streaming, shown, streamSpeed]);
useEffect(() => () => clearTimeout(timer.current), []);
const copy = async () => {
try {
await navigator.clipboard.writeText(text);
} catch {
// Clipboard blocked or unavailable: no check mark.
return;
}
setCopied(true);
clearTimeout(timer.current);
timer.current = setTimeout(() => setCopied(false), COPIED_MS);
};
const rate = (value: "like" | "dislike") => {
const next = feedback === value ? null : value;
setFeedback(next);
onFeedback?.(next);
};
const timeEl = timeText && <time className={time}>{timeText}</time>;
return (
<article
data-from={from}
aria-label={assistant ? assistantLabel : userLabel}
className={cx(roots[from], className)}
{...props}
>
{assistant && (
<span aria-hidden="true" className={avatar}>
{avatarSrc ? (
<img src={avatarSrc} alt="" className={avatarImage} />
) : (
<Icon d={PATHS.spark} className={avatarIcon} />
)}
</span>
)}
<div className={bodies[from]}>
{assistant && (
<p className={header}>
{assistantLabel}
{timeEl}
</p>
)}
<div className={contents[assistant ? variant : "user"]}>
{typing ? (
<span role="status" className={dots}>
<span className={srOnly}>{typingLabel}</span>
{dot.map((c) => (
<span key={c} aria-hidden="true" className={c} />
))}
</span>
) : stream ? (
<>
<span className={srOnly}>{text}</span>
<span aria-hidden="true">{tokens.slice(0, shown).join("")}</span>
{streaming && <span aria-hidden="true" className={caret} />}
</>
) : (
text
)}
</div>
<div className={footer}>
{showActions && !typing && !streaming && (
<div role="group" aria-label={actionsLabel} className={actions}>
<button
type="button"
aria-label={copyLabel}
data-state={copied ? "copied" : "idle"}
className={action}
onClick={copy}
>
<Icon d={PATHS.copy} className={copyIcon} />
<Icon d={PATHS.check} className={checkIcon} />
</button>
{assistant && (
<>
<button
type="button"
aria-label={likeLabel}
aria-pressed={feedback === "like"}
className={action}
onClick={() => rate("like")}
>
<Icon d={PATHS.like} className={pressIcon} />
</button>
<button
type="button"
aria-label={dislikeLabel}
aria-pressed={feedback === "dislike"}
className={action}
onClick={() => rate("dislike")}
>
<Icon d={PATHS.dislike} className={pressIcon} />
</button>
<button
type="button"
aria-label={regenerateLabel}
className={action}
onClick={onRegenerate}
>
<Icon d={PATHS.regenerate} className={actionIcon} />
</button>
</>
)}
<span role="status" className={srOnly}>
{copied ? copiedLabel : ""}
</span>
</div>
)}
{!assistant && timeEl}
</div>
</div>
</article>
);
}- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/components/markas/ChatMessage.vue.
src/components/markas/ChatMessage.vue
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
export type ChatMessageFeedback = "like" | "dislike" | null;
const props = withDefaults(
defineProps<{
from?: "user" | "assistant";
text?: string;
/** Assistant messages: plain text or a soft bubble. */
variant?: "plain" | "bubble";
time?: string;
/** Image URL for the assistant avatar. Defaults to a spark icon. */
avatar?: string;
/** Shows three dots instead of the text. */
typing?: boolean;
/** Reveals the text token by token with a caret. Off with reduced motion. */
stream?: boolean;
/** Pause between streamed tokens, in ms. */
streamSpeed?: number;
/** Shows copy, and for the assistant like, dislike, and regenerate. */
actions?: boolean;
userLabel?: string;
assistantLabel?: string;
typingLabel?: string;
actionsLabel?: string;
copyLabel?: string;
copiedLabel?: string;
likeLabel?: string;
dislikeLabel?: string;
regenerateLabel?: string;
}>(),
{
from: "assistant",
text: "",
variant: "plain",
time: undefined,
avatar: undefined,
typing: false,
stream: false,
streamSpeed: 40,
actions: true,
userLabel: "You",
assistantLabel: "Assistant",
typingLabel: "Typing",
actionsLabel: "Message actions",
copyLabel: "Copy",
copiedLabel: "Copied",
likeLabel: "Good response",
dislikeLabel: "Bad response",
regenerateLabel: "Regenerate",
},
);
const emit = defineEmits<{
feedback: [value: ChatMessageFeedback];
regenerate: [];
}>();
const roots = {
user: "group/message flex flex-col items-end gap-1",
assistant: "group/message flex items-start gap-3",
};
const avatarClass =
"grid size-8 shrink-0 place-items-center overflow-hidden rounded-full border border-line bg-surface text-ink";
const avatarImage = "size-full object-cover";
const avatarIcon = "size-4";
const bodies = {
user: "flex w-full flex-col items-end gap-1",
assistant: "grid min-w-0 flex-1 justify-items-start gap-1",
};
const header = "flex items-baseline gap-2 text-sm font-medium text-ink";
const contents = {
user: "max-w-[85%] rounded-2xl rounded-br-md bg-primary px-4 py-2.5 text-sm leading-6 break-words whitespace-pre-line text-on-primary",
plain: "text-sm leading-6 break-words whitespace-pre-line text-ink",
bubble:
"rounded-2xl rounded-tl-md bg-subtle px-4 py-2.5 text-sm leading-6 break-words whitespace-pre-line text-ink",
};
const timeClass = "text-xs font-normal text-muted";
const footer = "flex min-h-7 items-center gap-1";
const actionsClass =
"flex items-center gap-0.5 opacity-0 transition-opacity duration-150 ease-out group-focus-within/message:opacity-100 group-hover/message:opacity-100 motion-reduce:transition-none [@media(hover:none)]:opacity-100";
const action =
"group/action grid size-7 place-items-center rounded-md text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary aria-pressed:text-ink motion-reduce:transition-none";
const actionIcon = "col-start-1 row-start-1 size-4";
const pressIcon = "size-4 group-aria-pressed/action:fill-current/20";
const copyIcon =
"col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]/action:scale-50 group-data-[state=copied]/action:opacity-0 motion-reduce:transition-none";
const checkIcon =
"col-start-1 row-start-1 size-4 scale-50 opacity-0 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]/action:scale-100 group-data-[state=copied]/action:opacity-100 motion-reduce:transition-none";
const dots = "inline-flex h-6 items-center gap-1";
const dot = [
"size-1.5 animate-pulse rounded-full bg-muted motion-reduce:animate-none",
"size-1.5 animate-pulse rounded-full bg-muted [animation-delay:150ms] motion-reduce:animate-none",
"size-1.5 animate-pulse rounded-full bg-muted [animation-delay:300ms] motion-reduce:animate-none",
];
const caret =
"ml-0.5 inline-block h-4 w-1.5 translate-y-0.5 animate-pulse rounded-xs bg-current motion-reduce:animate-none";
const srOnly = "sr-only";
const PATHS = {
spark:
"M12 3c.4 4.6 2.4 6.6 7 7-4.6.4-6.6 2.4-7 7-.4-4.6-2.4-6.6-7-7 4.6-.4 6.6-2.4 7-7zM19 16c.2 1.6.9 2.3 2.5 2.5-1.6.2-2.3.9-2.5 2.5-.2-1.6-.9-2.3-2.5-2.5 1.6-.2 2.3-.9 2.5-2.5z",
copy: "M9 9h10a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H11a2 2 0 0 1-2-2zM5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1",
check: "m4 12 5 5L20 6",
like: "M7 10v11M15 5.9 14 10h5.8a2 2 0 0 1 1.9 2.6l-2.3 8a2 2 0 0 1-1.9 1.4H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.8a2 2 0 0 0 1.8-1.1L12 2a3.1 3.1 0 0 1 3 3.9z",
dislike:
"M17 14V3M9 18.1 10 14H4.2a2 2 0 0 1-1.9-2.6l2.3-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.8a2 2 0 0 0-1.8 1.1L12 22a3.1 3.1 0 0 1-3-3.9z",
regenerate:
"M3 12a9 9 0 0 1 15.7-6L21 8M21 3v5h-5M21 12a9 9 0 0 1-15.7 6L3 16M8 16H3v5",
};
/** How long the check mark stays after copying. */
const COPIED_MS = 2000;
const reducedMotion = () =>
typeof matchMedia === "function" &&
matchMedia("(prefers-reduced-motion: reduce)").matches;
/** Words and the spaces between them, so streaming reveals one token at a time. */
const tokens = computed(() => props.text.split(/(\s+)/).filter(Boolean));
const shown = ref(Infinity);
const copied = ref(false);
const feedback = ref<ChatMessageFeedback>(null);
const assistant = computed(() => props.from === "assistant");
const streaming = computed(
() => props.stream && shown.value < tokens.value.length,
);
let timer: ReturnType<typeof setTimeout> | undefined;
let tick: ReturnType<typeof setTimeout> | undefined;
onMounted(() => {
if (props.stream && !reducedMotion()) shown.value = 0;
});
watch(
[streaming, shown],
() => {
clearTimeout(tick);
if (streaming.value)
tick = setTimeout(() => shown.value++, props.streamSpeed);
},
{ flush: "post" },
);
onBeforeUnmount(() => {
clearTimeout(timer);
clearTimeout(tick);
});
async function copy() {
try {
await navigator.clipboard.writeText(props.text);
} catch {
// Clipboard blocked or unavailable: no check mark.
return;
}
copied.value = true;
clearTimeout(timer);
timer = setTimeout(() => (copied.value = false), COPIED_MS);
}
function rate(value: "like" | "dislike") {
feedback.value = feedback.value === value ? null : value;
emit("feedback", feedback.value);
}
</script>
<template>
<article
:data-from="props.from"
:aria-label="assistant ? props.assistantLabel : props.userLabel"
:class="roots[props.from]"
>
<span v-if="assistant" aria-hidden="true" :class="avatarClass">
<img
v-if="props.avatar"
:src="props.avatar"
alt=""
:class="avatarImage"
/>
<svg
v-else
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
:class="avatarIcon"
>
<path :d="PATHS.spark" />
</svg>
</span>
<div :class="bodies[props.from]">
<p v-if="assistant" :class="header">
{{ props.assistantLabel
}}<time v-if="props.time" :class="timeClass">{{ props.time }}</time>
</p>
<div :class="contents[assistant ? props.variant : 'user']">
<span v-if="props.typing" role="status" :class="dots"
><span :class="srOnly">{{ props.typingLabel }}</span
><span v-for="c in dot" :key="c" aria-hidden="true" :class="c"
/></span>
<template v-else-if="props.stream"
><span :class="srOnly">{{ props.text }}</span
><span aria-hidden="true">{{ tokens.slice(0, shown).join("") }}</span
><span v-if="streaming" aria-hidden="true" :class="caret"
/></template>
<template v-else>{{ props.text }}</template>
</div>
<div :class="footer">
<div
v-if="props.actions && !props.typing && !streaming"
role="group"
:aria-label="props.actionsLabel"
:class="actionsClass"
>
<button
type="button"
:aria-label="props.copyLabel"
:data-state="copied ? 'copied' : 'idle'"
:class="action"
@click="copy"
>
<svg
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
:class="copyIcon"
>
<path :d="PATHS.copy" />
</svg>
<svg
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
:class="checkIcon"
>
<path :d="PATHS.check" />
</svg>
</button>
<template v-if="assistant">
<button
v-for="value in ['like', 'dislike'] as const"
:key="value"
type="button"
:aria-label="
value === 'like' ? props.likeLabel : props.dislikeLabel
"
:aria-pressed="feedback === value"
:class="action"
@click="rate(value)"
>
<svg
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
:class="pressIcon"
>
<path :d="PATHS[value]" />
</svg>
</button>
<button
type="button"
:aria-label="props.regenerateLabel"
:class="action"
@click="emit('regenerate')"
>
<svg
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
:class="actionIcon"
>
<path :d="PATHS.regenerate" />
</svg>
</button>
</template>
<span role="status" :class="srOnly">{{
copied ? props.copiedLabel : ""
}}</span>
</div>
<time v-if="!assistant && props.time" :class="timeClass">{{
props.time
}}</time>
</div>
</div>
</article>
</template>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/lib/components/markas/ChatMessage.svelte.
src/lib/components/markas/ChatMessage.svelte
<script lang="ts" module>
export type ChatMessageFeedback = "like" | "dislike" | null;
</script>
<script lang="ts">
import { onDestroy } from "svelte";
import type { HTMLAttributes } from "svelte/elements";
const roots = {
user: "group/message flex flex-col items-end gap-1",
assistant: "group/message flex items-start gap-3",
};
const avatarClass =
"grid size-8 shrink-0 place-items-center overflow-hidden rounded-full border border-line bg-surface text-ink";
const avatarImage = "size-full object-cover";
const avatarIcon = "size-4";
const bodies = {
user: "flex w-full flex-col items-end gap-1",
assistant: "grid min-w-0 flex-1 justify-items-start gap-1",
};
const header = "flex items-baseline gap-2 text-sm font-medium text-ink";
const contents = {
user: "max-w-[85%] rounded-2xl rounded-br-md bg-primary px-4 py-2.5 text-sm leading-6 break-words whitespace-pre-line text-on-primary",
plain: "text-sm leading-6 break-words whitespace-pre-line text-ink",
bubble:
"rounded-2xl rounded-tl-md bg-subtle px-4 py-2.5 text-sm leading-6 break-words whitespace-pre-line text-ink",
};
const timeClass = "text-xs font-normal text-muted";
const footer = "flex min-h-7 items-center gap-1";
const actionsClass =
"flex items-center gap-0.5 opacity-0 transition-opacity duration-150 ease-out group-focus-within/message:opacity-100 group-hover/message:opacity-100 motion-reduce:transition-none [@media(hover:none)]:opacity-100";
const action =
"group/action grid size-7 place-items-center rounded-md text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary aria-pressed:text-ink motion-reduce:transition-none";
const actionIcon = "col-start-1 row-start-1 size-4";
const pressIcon = "size-4 group-aria-pressed/action:fill-current/20";
const copyIcon =
"col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]/action:scale-50 group-data-[state=copied]/action:opacity-0 motion-reduce:transition-none";
const checkIcon =
"col-start-1 row-start-1 size-4 scale-50 opacity-0 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]/action:scale-100 group-data-[state=copied]/action:opacity-100 motion-reduce:transition-none";
const dots = "inline-flex h-6 items-center gap-1";
const dot = [
"size-1.5 animate-pulse rounded-full bg-muted motion-reduce:animate-none",
"size-1.5 animate-pulse rounded-full bg-muted [animation-delay:150ms] motion-reduce:animate-none",
"size-1.5 animate-pulse rounded-full bg-muted [animation-delay:300ms] motion-reduce:animate-none",
];
const caret =
"ml-0.5 inline-block h-4 w-1.5 translate-y-0.5 animate-pulse rounded-xs bg-current motion-reduce:animate-none";
const srOnly = "sr-only";
const PATHS = {
spark:
"M12 3c.4 4.6 2.4 6.6 7 7-4.6.4-6.6 2.4-7 7-.4-4.6-2.4-6.6-7-7 4.6-.4 6.6-2.4 7-7zM19 16c.2 1.6.9 2.3 2.5 2.5-1.6.2-2.3.9-2.5 2.5-.2-1.6-.9-2.3-2.5-2.5 1.6-.2 2.3-.9 2.5-2.5z",
copy: "M9 9h10a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H11a2 2 0 0 1-2-2zM5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1",
check: "m4 12 5 5L20 6",
like: "M7 10v11M15 5.9 14 10h5.8a2 2 0 0 1 1.9 2.6l-2.3 8a2 2 0 0 1-1.9 1.4H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.8a2 2 0 0 0 1.8-1.1L12 2a3.1 3.1 0 0 1 3 3.9z",
dislike:
"M17 14V3M9 18.1 10 14H4.2a2 2 0 0 1-1.9-2.6l2.3-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.8a2 2 0 0 0-1.8 1.1L12 22a3.1 3.1 0 0 1-3-3.9z",
regenerate:
"M3 12a9 9 0 0 1 15.7-6L21 8M21 3v5h-5M21 12a9 9 0 0 1-15.7 6L3 16M8 16H3v5",
};
/** How long the check mark stays after copying. */
const COPIED_MS = 2000;
const reducedMotion = () =>
typeof matchMedia === "function" &&
matchMedia("(prefers-reduced-motion: reduce)").matches;
type Props = HTMLAttributes<HTMLElement> & {
from?: "user" | "assistant";
text?: string;
/** Assistant messages: plain text or a soft bubble. */
variant?: "plain" | "bubble";
time?: string;
/** Image URL for the assistant avatar. Defaults to a spark icon. */
avatar?: string;
/** Shows three dots instead of the text. */
typing?: boolean;
/** Reveals the text token by token with a caret. Off with reduced motion. */
stream?: boolean;
/** Pause between streamed tokens, in ms. */
streamSpeed?: number;
/** Shows copy, and for the assistant like, dislike, and regenerate. */
actions?: boolean;
onFeedback?: (value: ChatMessageFeedback) => void;
onRegenerate?: () => void;
userLabel?: string;
assistantLabel?: string;
typingLabel?: string;
actionsLabel?: string;
copyLabel?: string;
copiedLabel?: string;
likeLabel?: string;
dislikeLabel?: string;
regenerateLabel?: string;
};
let {
from = "assistant",
text = "",
variant = "plain",
time,
avatar,
typing = false,
stream = false,
streamSpeed = 40,
actions = true,
onFeedback,
onRegenerate,
userLabel = "You",
assistantLabel = "Assistant",
typingLabel = "Typing",
actionsLabel = "Message actions",
copyLabel = "Copy",
copiedLabel = "Copied",
likeLabel = "Good response",
dislikeLabel = "Bad response",
regenerateLabel = "Regenerate",
class: className,
...rest
}: Props = $props();
const assistant = $derived(from === "assistant");
/** Words and the spaces between them, so streaming reveals one token at a time. */
const tokens = $derived(text.split(/(\s+)/).filter(Boolean));
let shown = $state(Infinity);
let copied = $state(false);
let feedback = $state<ChatMessageFeedback>(null);
const streaming = $derived(stream && shown < tokens.length);
let timer: ReturnType<typeof setTimeout> | undefined;
$effect.pre(() => {
if (stream && !reducedMotion()) shown = 0;
});
$effect(() => {
if (!streaming) return;
// Read shown here so the effect re-runs after every token (React: deps [streaming, shown]).
const current = shown;
const next = setTimeout(() => (shown = current + 1), streamSpeed);
return () => clearTimeout(next);
});
onDestroy(() => clearTimeout(timer));
async function copy() {
try {
await navigator.clipboard.writeText(text);
} catch {
// Clipboard blocked or unavailable: no check mark.
return;
}
copied = true;
clearTimeout(timer);
timer = setTimeout(() => (copied = false), COPIED_MS);
}
function rate(value: "like" | "dislike") {
feedback = feedback === value ? null : value;
onFeedback?.(feedback);
}
</script>
{#snippet icon(d: string, iconClass: string)}
<svg
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
class={iconClass}
>
<path {d} />
</svg>
{/snippet}
<article
data-from={from}
aria-label={assistant ? assistantLabel : userLabel}
class={[roots[from], className]}
{...rest}
>
{#if assistant}
<span aria-hidden="true" class={avatarClass}>
{#if avatar}
<img src={avatar} alt="" class={avatarImage} />
{:else}
{@render icon(PATHS.spark, avatarIcon)}
{/if}
</span>
{/if}
<div class={bodies[from]}>
{#if assistant}
<p class={header}>
{assistantLabel}{#if time}<time class={timeClass}>{time}</time>{/if}
</p>
{/if}
<div class={contents[assistant ? variant : "user"]}>
{#if typing}<span role="status" class={dots}
><span class={srOnly}>{typingLabel}</span>{#each dot as c (c)}<span
aria-hidden="true"
class={c}
></span>{/each}</span
>{:else if stream}<span class={srOnly}>{text}</span><span
aria-hidden="true">{tokens.slice(0, shown).join("")}</span
>{#if streaming}<span aria-hidden="true" class={caret}
></span>{/if}{:else}{text}{/if}
</div>
<div class={footer}>
{#if actions && !typing && !streaming}
<div role="group" aria-label={actionsLabel} class={actionsClass}>
<button
type="button"
aria-label={copyLabel}
data-state={copied ? "copied" : "idle"}
class={action}
onclick={copy}
>
{@render icon(PATHS.copy, copyIcon)}
{@render icon(PATHS.check, checkIcon)}
</button>
{#if assistant}
<button
type="button"
aria-label={likeLabel}
aria-pressed={feedback === "like"}
class={action}
onclick={() => rate("like")}
>
{@render icon(PATHS.like, pressIcon)}
</button>
<button
type="button"
aria-label={dislikeLabel}
aria-pressed={feedback === "dislike"}
class={action}
onclick={() => rate("dislike")}
>
{@render icon(PATHS.dislike, pressIcon)}
</button>
<button
type="button"
aria-label={regenerateLabel}
class={action}
onclick={onRegenerate}
>
{@render icon(PATHS.regenerate, actionIcon)}
</button>
{/if}
<span role="status" class={srOnly}>{copied ? copiedLabel : ""}</span>
</div>
{/if}
{#if !assistant && time}<time class={timeClass}>{time}</time>{/if}
</div>
</div>
</article>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/components/markas/ChatMessage.astro.
src/components/markas/ChatMessage.astro
---
import type { HTMLAttributes } from "astro/types";
const roots = {
user: "group/message flex flex-col items-end gap-1",
assistant: "group/message flex items-start gap-3",
};
const avatarClass =
"grid size-8 shrink-0 place-items-center overflow-hidden rounded-full border border-line bg-surface text-ink";
const avatarImage = "size-full object-cover";
const avatarIcon = "size-4";
const bodies = {
user: "flex w-full flex-col items-end gap-1",
assistant: "grid min-w-0 flex-1 justify-items-start gap-1",
};
const header = "flex items-baseline gap-2 text-sm font-medium text-ink";
const contents = {
user: "max-w-[85%] rounded-2xl rounded-br-md bg-primary px-4 py-2.5 text-sm leading-6 break-words whitespace-pre-line text-on-primary",
plain: "text-sm leading-6 break-words whitespace-pre-line text-ink",
bubble:
"rounded-2xl rounded-tl-md bg-subtle px-4 py-2.5 text-sm leading-6 break-words whitespace-pre-line text-ink",
};
const timeClass = "text-xs font-normal text-muted";
const footer = "flex min-h-7 items-center gap-1";
const actionsClass =
"flex items-center gap-0.5 opacity-0 transition-opacity duration-150 ease-out group-focus-within/message:opacity-100 group-hover/message:opacity-100 motion-reduce:transition-none [@media(hover:none)]:opacity-100";
const action =
"group/action grid size-7 place-items-center rounded-md text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary aria-pressed:text-ink motion-reduce:transition-none";
const actionIcon = "col-start-1 row-start-1 size-4";
const pressIcon = "size-4 group-aria-pressed/action:fill-current/20";
const copyIcon =
"col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]/action:scale-50 group-data-[state=copied]/action:opacity-0 motion-reduce:transition-none";
const checkIcon =
"col-start-1 row-start-1 size-4 scale-50 opacity-0 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]/action:scale-100 group-data-[state=copied]/action:opacity-100 motion-reduce:transition-none";
const dots = "inline-flex h-6 items-center gap-1";
const dot = [
"size-1.5 animate-pulse rounded-full bg-muted motion-reduce:animate-none",
"size-1.5 animate-pulse rounded-full bg-muted [animation-delay:150ms] motion-reduce:animate-none",
"size-1.5 animate-pulse rounded-full bg-muted [animation-delay:300ms] motion-reduce:animate-none",
];
const caret =
"ml-0.5 inline-block h-4 w-1.5 translate-y-0.5 animate-pulse rounded-xs bg-current motion-reduce:animate-none";
const srOnly = "sr-only";
const PATHS = {
spark:
"M12 3c.4 4.6 2.4 6.6 7 7-4.6.4-6.6 2.4-7 7-.4-4.6-2.4-6.6-7-7 4.6-.4 6.6-2.4 7-7zM19 16c.2 1.6.9 2.3 2.5 2.5-1.6.2-2.3.9-2.5 2.5-.2-1.6-.9-2.3-2.5-2.5 1.6-.2 2.3-.9 2.5-2.5z",
copy: "M9 9h10a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H11a2 2 0 0 1-2-2zM5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1",
check: "m4 12 5 5L20 6",
like: "M7 10v11M15 5.9 14 10h5.8a2 2 0 0 1 1.9 2.6l-2.3 8a2 2 0 0 1-1.9 1.4H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.8a2 2 0 0 0 1.8-1.1L12 2a3.1 3.1 0 0 1 3 3.9z",
dislike:
"M17 14V3M9 18.1 10 14H4.2a2 2 0 0 1-1.9-2.6l2.3-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.8a2 2 0 0 0-1.8 1.1L12 22a3.1 3.1 0 0 1-3-3.9z",
regenerate:
"M3 12a9 9 0 0 1 15.7-6L21 8M21 3v5h-5M21 12a9 9 0 0 1-15.7 6L3 16M8 16H3v5",
};
type Props = HTMLAttributes<"article"> & {
from?: "user" | "assistant";
text?: string;
/** Assistant messages: plain text or a soft bubble. */
variant?: "plain" | "bubble";
time?: string;
/** Image URL for the assistant avatar. Defaults to a spark icon. */
avatar?: string;
/** Shows three dots instead of the text. */
typing?: boolean;
/** Reveals the text token by token with a caret. Off with reduced motion. */
stream?: boolean;
/** Pause between streamed tokens, in ms. */
streamSpeed?: number;
/** Shows copy, and for the assistant like, dislike, and regenerate. */
actions?: boolean;
userLabel?: string;
assistantLabel?: string;
typingLabel?: string;
actionsLabel?: string;
copyLabel?: string;
copiedLabel?: string;
likeLabel?: string;
dislikeLabel?: string;
regenerateLabel?: string;
};
const {
from = "assistant",
text = "",
variant = "plain",
time,
avatar,
typing = false,
stream = false,
streamSpeed = 40,
actions = true,
userLabel = "You",
assistantLabel = "Assistant",
typingLabel = "Typing",
actionsLabel = "Message actions",
copyLabel = "Copy",
copiedLabel = "Copied",
likeLabel = "Good response",
dislikeLabel = "Bad response",
regenerateLabel = "Regenerate",
class: className,
...rest
} = Astro.props;
const assistant = from === "assistant";
const feedbackButtons = [
{ value: "like", label: likeLabel, d: PATHS.like },
{ value: "dislike", label: dislikeLabel, d: PATHS.dislike },
];
---
<markas-chat-message
class="contents"
data-stream={stream ? String(streamSpeed) : undefined}
data-copied-label={copiedLabel}
data-text={text}
>
<article
data-from={from}
aria-label={assistant ? assistantLabel : userLabel}
class:list={[roots[from], className]}
{...rest}
>
{
assistant && (
<span aria-hidden="true" class={avatarClass}>
{avatar ? (
<img src={avatar} alt="" class={avatarImage} />
) : (
<svg
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
class={avatarIcon}
>
<path d={PATHS.spark} />
</svg>
)}
</span>
)
}
<div class={bodies[from]}>
{
assistant && (
<p class={header}>
{assistantLabel}
{time && <time class={timeClass}>{time}</time>}
</p>
)
}
<div class={contents[assistant ? variant : "user"]}>{typing ? (<span role="status" class={dots}><span class={srOnly}>{typingLabel}</span>{dot.map((c) => (<span aria-hidden="true" class={c} />))}</span>) : stream ? (<Fragment><span class={srOnly}>{text}</span><span aria-hidden="true" data-text={text}>{text}</span><span aria-hidden="true" class={caret} data-caret hidden /></Fragment>) : text}</div>
<div class={footer}>
{
actions && !typing && (
<div
role="group"
aria-label={actionsLabel}
class={actionsClass}
data-actions
>
<button
type="button"
aria-label={copyLabel}
data-state="idle"
data-copy
class={action}
>
<svg
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
class={copyIcon}
>
<path d={PATHS.copy} />
</svg>
<svg
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
class={checkIcon}
>
<path d={PATHS.check} />
</svg>
</button>
{assistant && (
<Fragment>
{feedbackButtons.map((button) => (
<button
type="button"
aria-label={button.label}
aria-pressed="false"
data-feedback={button.value}
class={action}
>
<svg
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
class={pressIcon}
>
<path d={button.d} />
</svg>
</button>
))}
<button
type="button"
aria-label={regenerateLabel}
data-regenerate
class={action}
>
<svg
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
class={actionIcon}
>
<path d={PATHS.regenerate} />
</svg>
</button>
</Fragment>
)}
<span role="status" class={srOnly} data-status />
</div>
)
}
{!assistant && time && <time class={timeClass}>{time}</time>}
</div>
</div>
</article>
</markas-chat-message>
<script>
/** How long the check mark stays after copying. */
const COPIED_MS = 2000;
// Each message streams and copies on its own, so it is a custom element: it also works
// for markup added later and for pages reached through view transitions.
class MarkasChatMessage extends HTMLElement {
private timer: ReturnType<typeof setTimeout> | undefined;
private tick: ReturnType<typeof setTimeout> | undefined;
private ready = false;
connectedCallback() {
if (this.ready) return;
this.ready = true;
this.addEventListener("click", (event) => this.onClick(event));
this.startStream();
}
disconnectedCallback() {
clearTimeout(this.timer);
clearTimeout(this.tick);
}
/** Reveal the text one token (a word or the spaces after it) at a time. */
private startStream() {
const speed = Number(this.dataset.stream);
const visible = this.querySelector<HTMLElement>("[data-text]");
if (
this.dataset.stream === undefined ||
!visible ||
matchMedia("(prefers-reduced-motion: reduce)").matches
)
return;
const tokens = (visible.dataset.text ?? "")
.split(/(\s+)/)
.filter(Boolean);
const caret = this.querySelector<HTMLElement>("[data-caret]");
const actions = this.querySelector<HTMLElement>("[data-actions]");
let shown = 0;
const render = () => {
const streaming = shown < tokens.length;
visible.textContent = tokens.slice(0, shown).join("");
if (caret) caret.hidden = !streaming;
if (actions) actions.hidden = streaming;
if (!streaming) return;
shown++;
this.tick = setTimeout(render, speed);
};
render();
}
private async onClick(event: Event) {
const target = event.target as Element;
const copy = target.closest<HTMLElement>("[data-copy]");
const feedback = target.closest<HTMLElement>("[data-feedback]");
if (target.closest("[data-regenerate]"))
this.dispatchEvent(
new CustomEvent("markas-regenerate", { bubbles: true }),
);
if (feedback) this.rate(feedback);
if (copy) await this.copy(copy);
}
private rate(button: HTMLElement) {
const pressed = button.getAttribute("aria-pressed") !== "true";
this.querySelectorAll("[data-feedback]").forEach((other) =>
other.setAttribute("aria-pressed", "false"),
);
button.setAttribute("aria-pressed", String(pressed));
this.dispatchEvent(
new CustomEvent("markas-feedback", {
detail: pressed ? button.dataset.feedback : null,
bubbles: true,
}),
);
}
private async copy(button: HTMLElement) {
try {
await navigator.clipboard.writeText(this.dataset.text ?? "");
} catch {
// Clipboard blocked or unavailable: no check mark.
return;
}
const status = this.querySelector("[data-status]");
const setCopied = (copied: boolean) => {
button.dataset.state = copied ? "copied" : "idle";
if (status)
status.textContent = copied ? (this.dataset.copiedLabel ?? "") : "";
};
setCopied(true);
clearTimeout(this.timer);
this.timer = setTimeout(() => setCopied(false), COPIED_MS);
}
}
if (!customElements.get("markas-chat-message"))
customElements.define("markas-chat-message", MarkasChatMessage);
</script>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/app/markas/chat-message.component.ts.
src/app/markas/chat-message.component.ts
import { NgTemplateOutlet } from "@angular/common";
import {
afterNextRender,
booleanAttribute,
ChangeDetectionStrategy,
Component,
computed,
DestroyRef,
effect,
inject,
input,
numberAttribute,
output,
signal,
} from "@angular/core";
const roots = {
user: "group/message flex flex-col items-end gap-1",
assistant: "group/message flex items-start gap-3",
};
const avatarClass =
"grid size-8 shrink-0 place-items-center overflow-hidden rounded-full border border-line bg-surface text-ink";
const avatarImage = "size-full object-cover";
const avatarIcon = "size-4";
const bodies = {
user: "flex w-full flex-col items-end gap-1",
assistant: "grid min-w-0 flex-1 justify-items-start gap-1",
};
const header = "flex items-baseline gap-2 text-sm font-medium text-ink";
const contents = {
user: "max-w-[85%] rounded-2xl rounded-br-md bg-primary px-4 py-2.5 text-sm leading-6 break-words whitespace-pre-line text-on-primary",
plain: "text-sm leading-6 break-words whitespace-pre-line text-ink",
bubble:
"rounded-2xl rounded-tl-md bg-subtle px-4 py-2.5 text-sm leading-6 break-words whitespace-pre-line text-ink",
};
const timeClass = "text-xs font-normal text-muted";
const footer = "flex min-h-7 items-center gap-1";
const actionsClass =
"flex items-center gap-0.5 opacity-0 transition-opacity duration-150 ease-out group-focus-within/message:opacity-100 group-hover/message:opacity-100 motion-reduce:transition-none [@media(hover:none)]:opacity-100";
const action =
"group/action grid size-7 place-items-center rounded-md text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary aria-pressed:text-ink motion-reduce:transition-none";
const actionIcon = "col-start-1 row-start-1 size-4";
const pressIcon = "size-4 group-aria-pressed/action:fill-current/20";
const copyIcon =
"col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]/action:scale-50 group-data-[state=copied]/action:opacity-0 motion-reduce:transition-none";
const checkIcon =
"col-start-1 row-start-1 size-4 scale-50 opacity-0 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]/action:scale-100 group-data-[state=copied]/action:opacity-100 motion-reduce:transition-none";
const dots = "inline-flex h-6 items-center gap-1";
const dot = [
"size-1.5 animate-pulse rounded-full bg-muted motion-reduce:animate-none",
"size-1.5 animate-pulse rounded-full bg-muted [animation-delay:150ms] motion-reduce:animate-none",
"size-1.5 animate-pulse rounded-full bg-muted [animation-delay:300ms] motion-reduce:animate-none",
];
const caret =
"ml-0.5 inline-block h-4 w-1.5 translate-y-0.5 animate-pulse rounded-xs bg-current motion-reduce:animate-none";
const srOnly = "sr-only";
const PATHS = {
spark:
"M12 3c.4 4.6 2.4 6.6 7 7-4.6.4-6.6 2.4-7 7-.4-4.6-2.4-6.6-7-7 4.6-.4 6.6-2.4 7-7zM19 16c.2 1.6.9 2.3 2.5 2.5-1.6.2-2.3.9-2.5 2.5-.2-1.6-.9-2.3-2.5-2.5 1.6-.2 2.3-.9 2.5-2.5z",
copy: "M9 9h10a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H11a2 2 0 0 1-2-2zM5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1",
check: "m4 12 5 5L20 6",
like: "M7 10v11M15 5.9 14 10h5.8a2 2 0 0 1 1.9 2.6l-2.3 8a2 2 0 0 1-1.9 1.4H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.8a2 2 0 0 0 1.8-1.1L12 2a3.1 3.1 0 0 1 3 3.9z",
dislike:
"M17 14V3M9 18.1 10 14H4.2a2 2 0 0 1-1.9-2.6l2.3-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.8a2 2 0 0 0-1.8 1.1L12 22a3.1 3.1 0 0 1-3-3.9z",
regenerate:
"M3 12a9 9 0 0 1 15.7-6L21 8M21 3v5h-5M21 12a9 9 0 0 1-15.7 6L3 16M8 16H3v5",
};
/** How long the check mark stays after copying. */
const COPIED_MS = 2000;
const reducedMotion = () =>
typeof matchMedia === "function" &&
matchMedia("(prefers-reduced-motion: reduce)").matches;
export type ChatMessageFeedback = "like" | "dislike" | null;
/** Host stays out of layout; class moves to the article. */
@Component({
selector: "markas-chat-message",
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [NgTemplateOutlet],
host: { class: "contents" },
template: `
<ng-template #icon let-d let-iconClass="iconClass">
<svg
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
[class]="iconClass"
>
<path [attr.d]="d" />
</svg>
</ng-template>
<article
[attr.data-from]="from()"
[attr.aria-label]="assistant() ? assistantLabel() : userLabel()"
[class]="rootClasses()"
>
@if (assistant()) {
<span aria-hidden="true" [class]="avatarClass">
@if (avatar()) {
<img [src]="avatar()" alt="" [class]="avatarImage" />
} @else {
<ng-container
[ngTemplateOutlet]="icon"
[ngTemplateOutletContext]="{
$implicit: PATHS.spark,
iconClass: avatarIcon,
}"
/>
}
</span>
}
<div [class]="bodies[from()]">
@if (assistant()) {
<p [class]="header">
{{ assistantLabel() }}
@if (time()) {
<time [class]="timeClass">{{ time() }}</time>
}
</p>
}
<div [class]="contentClass()">
@if (typing()) {
<span role="status" [class]="dots"
><span [class]="srOnly">{{ typingLabel() }}</span>
@for (c of dot; track c) {
<span aria-hidden="true" [class]="c"></span>
}
</span>
} @else if (stream()) {
<span [class]="srOnly">{{ text() }}</span
><span aria-hidden="true">{{ visibleText() }}</span>
@if (streaming()) {
<span aria-hidden="true" [class]="caret"></span>
}
} @else {
<ng-container>{{ text() }}</ng-container>
}
</div>
<div [class]="footer">
@if (actions() && !typing() && !streaming()) {
<div
role="group"
[attr.aria-label]="actionsLabel()"
[class]="actionsClass"
>
<button
type="button"
[attr.aria-label]="copyLabel()"
[attr.data-state]="copied() ? 'copied' : 'idle'"
[class]="action"
(click)="copy()"
>
<ng-container
[ngTemplateOutlet]="icon"
[ngTemplateOutletContext]="{
$implicit: PATHS.copy,
iconClass: copyIcon,
}"
/>
<ng-container
[ngTemplateOutlet]="icon"
[ngTemplateOutletContext]="{
$implicit: PATHS.check,
iconClass: checkIcon,
}"
/>
</button>
@if (assistant()) {
<button
type="button"
[attr.aria-label]="likeLabel()"
[attr.aria-pressed]="rating() === 'like'"
[class]="action"
(click)="rate('like')"
>
<ng-container
[ngTemplateOutlet]="icon"
[ngTemplateOutletContext]="{
$implicit: PATHS.like,
iconClass: pressIcon,
}"
/>
</button>
<button
type="button"
[attr.aria-label]="dislikeLabel()"
[attr.aria-pressed]="rating() === 'dislike'"
[class]="action"
(click)="rate('dislike')"
>
<ng-container
[ngTemplateOutlet]="icon"
[ngTemplateOutletContext]="{
$implicit: PATHS.dislike,
iconClass: pressIcon,
}"
/>
</button>
<button
type="button"
[attr.aria-label]="regenerateLabel()"
[class]="action"
(click)="regenerate.emit()"
>
<ng-container
[ngTemplateOutlet]="icon"
[ngTemplateOutletContext]="{
$implicit: PATHS.regenerate,
iconClass: actionIcon,
}"
/>
</button>
}
<span role="status" [class]="srOnly">{{
copied() ? copiedLabel() : ""
}}</span>
</div>
}
@if (!assistant() && time()) {
<time [class]="timeClass">{{ time() }}</time>
}
</div>
</div>
</article>
`,
})
export class ChatMessage {
readonly from = input<"user" | "assistant">("assistant");
readonly text = input("");
/** Assistant messages: plain text or a soft bubble. */
readonly variant = input<"plain" | "bubble">("plain");
readonly time = input<string>();
/** Image URL for the assistant avatar. Defaults to a spark icon. */
readonly avatar = input<string>();
/** Shows three dots instead of the text. */
readonly typing = input(false, { transform: booleanAttribute });
/** Reveals the text token by token with a caret. Off with reduced motion. */
readonly stream = input(false, { transform: booleanAttribute });
/** Pause between streamed tokens, in ms. */
readonly streamSpeed = input(40, { transform: numberAttribute });
/** Shows copy, and for the assistant like, dislike, and regenerate. */
readonly actions = input(true, { transform: booleanAttribute });
readonly userLabel = input("You");
readonly assistantLabel = input("Assistant");
readonly typingLabel = input("Typing");
readonly actionsLabel = input("Message actions");
readonly copyLabel = input("Copy");
readonly copiedLabel = input("Copied");
readonly likeLabel = input("Good response");
readonly dislikeLabel = input("Bad response");
readonly regenerateLabel = input("Regenerate");
readonly userClass = input("", { alias: "class" });
readonly feedback = output<ChatMessageFeedback>();
readonly regenerate = output<void>();
protected readonly PATHS = PATHS;
protected readonly avatarClass = avatarClass;
protected readonly avatarImage = avatarImage;
protected readonly avatarIcon = avatarIcon;
protected readonly bodies = bodies;
protected readonly header = header;
protected readonly timeClass = timeClass;
protected readonly footer = footer;
protected readonly actionsClass = actionsClass;
protected readonly action = action;
protected readonly actionIcon = actionIcon;
protected readonly pressIcon = pressIcon;
protected readonly copyIcon = copyIcon;
protected readonly checkIcon = checkIcon;
protected readonly dots = dots;
protected readonly dot = dot;
protected readonly caret = caret;
protected readonly srOnly = srOnly;
protected readonly copied = signal(false);
protected readonly rating = signal<ChatMessageFeedback>(null);
private readonly shown = signal(Infinity);
protected readonly assistant = computed(() => this.from() === "assistant");
/** Words and the spaces between them, so streaming reveals one token at a time. */
private readonly tokens = computed(() =>
this.text().split(/(\s+)/).filter(Boolean),
);
protected readonly streaming = computed(
() => this.stream() && this.shown() < this.tokens().length,
);
protected readonly visibleText = computed(() =>
this.tokens().slice(0, this.shown()).join(""),
);
protected readonly rootClasses = computed(() =>
[roots[this.from()], this.userClass()].filter(Boolean).join(" "),
);
protected readonly contentClass = computed(
() => contents[this.assistant() ? this.variant() : "user"],
);
private timer: ReturnType<typeof setTimeout> | undefined;
constructor() {
afterNextRender(() => {
if (this.stream() && !reducedMotion()) this.shown.set(0);
});
effect((onCleanup) => {
if (!this.streaming()) return;
// Read shown here so the effect re-runs after every token (React: deps [streaming, shown]).
const current = this.shown();
const next = setTimeout(
() => this.shown.set(current + 1),
this.streamSpeed(),
);
onCleanup(() => clearTimeout(next));
});
inject(DestroyRef).onDestroy(() => clearTimeout(this.timer));
}
protected async copy() {
try {
await navigator.clipboard.writeText(this.text());
} catch {
// Clipboard blocked or unavailable: no check mark.
return;
}
this.copied.set(true);
clearTimeout(this.timer);
this.timer = setTimeout(() => this.copied.set(false), COPIED_MS);
}
protected rate(value: "like" | "dislike") {
const next = this.rating() === value ? null : value;
this.rating.set(next);
this.feedback.emit(next);
}
}Usage
<div role="log" aria-label="Conversation" class="grid gap-5">
<x-markas.chat-message from="user" text="How do I bill a client in Rupiah?" time="10:24" />
<x-markas.chat-message
text="Set the currency to IDR and list each item with its amount."
time="10:24"
assistant-label="Markas AI"
x-on:feedback="rate($event.detail)"
x-on:regenerate="retry()"
/>
<x-markas.chat-message typing assistant-label="Markas AI" />
</div>import { ChatMessage } from "@/components/markas/ChatMessage";
<div role="log" aria-label="Conversation" className="grid gap-5">
<ChatMessage
from="user"
text="How do I bill a client in Rupiah?"
time="10:24"
/>
<ChatMessage
text={answer}
time="10:24"
assistantLabel="Markas AI"
stream
onFeedback={rate}
onRegenerate={retry}
/>
</div>;<script setup lang="ts">
import ChatMessage from "@/components/markas/ChatMessage.vue";
</script>
<template>
<div role="log" aria-label="Conversation" class="grid gap-5">
<ChatMessage
from="user"
text="How do I bill a client in Rupiah?"
time="10:24"
/>
<ChatMessage
:text="answer"
assistant-label="Markas AI"
variant="bubble"
@feedback="rate"
@regenerate="retry"
/>
</div>
</template><script lang="ts">
import ChatMessage from "$lib/components/markas/ChatMessage.svelte";
</script>
<div role="log" aria-label="Conversation" class="grid gap-5">
<ChatMessage
from="user"
text="How do I bill a client in Rupiah?"
time="10:24"
/>
<ChatMessage
text={answer}
time="10:24"
assistantLabel="Markas AI"
stream
onFeedback={rate}
onRegenerate={retry}
/>
</div>---
import ChatMessage from "@/components/markas/ChatMessage.astro";
---
<div role="log" aria-label="Conversation" class="grid gap-5">
<ChatMessage from="user" text="How do I bill a client in Rupiah?" time="10:24" />
<ChatMessage text={answer} time="10:24" assistantLabel="Markas AI" stream />
</div>A small custom element streams the text, copies it, and toggles the rating. It dispatches markas-feedback (the new value as detail) and markas-regenerate, both bubbling.
import { Component } from "@angular/core";
import { ChatMessage } from "./markas/chat-message.component";
@Component({
selector: "app-conversation",
imports: [ChatMessage],
template: `
<div role="log" aria-label="Conversation" class="grid gap-5">
<markas-chat-message
from="user"
text="How do I bill a client in Rupiah?"
/>
<markas-chat-message
[text]="answer"
assistantLabel="Markas AI"
stream
(feedback)="rate($event)"
(regenerate)="retry()"
/>
</div>
`,
})
export class Conversation {
answer = "Add the amount in Rupiah and a payment term.";
rate(value: "like" | "dislike" | null) {}
retry() {}
}- The action row fades in when the pointer is over the message or focus is inside it, so it never clutters the conversation.
- Copy shows a check for two seconds. Like and dislike are exclusive toggles and fire feedback with the new value.
- stream reveals the text one word at a time with a caret. If text grows while streaming, the reveal carries on to the new end.
- Reduced motion turns off the streaming, the dots pulse, and the fades.
Props
| Name | Type | Default | Description |
|---|---|---|---|
from | "user" | "assistant" | assistant | Who wrote it. User messages are a primary bubble on the right, assistant messages sit on the left with an avatar. |
text | string | "" | Message text. Line breaks are kept. Copy writes this text to the clipboard. |
variant | "plain" | "bubble" | plain | Assistant style: plain text, or a soft subtle bubble. |
time | string | - | Timestamp shown in a time element, next to the name for the assistant and under the bubble for the user. |
avatar | string | - | Image URL for the assistant avatar. Without it a spark icon is shown. |
typing | boolean | false | Shows three pulsing dots in place of the text, announced as typingLabel. |
stream | boolean | false | Reveals the text token by token with a caret, like a model streaming. With reduced motion the full text shows at once. |
streamSpeed | number | 40 | Pause between streamed tokens in ms. |
actions | boolean | true | Shows the action row on hover and focus: copy, plus like, dislike, and regenerate for the assistant. Hidden while typing or streaming. |
onFeedback / @feedback / x-on:feedback | (value: "like" | "dislike" | null) => void | - | Fires when like or dislike is toggled. Pressing the active one again sends null. |
onRegenerate / @regenerate / x-on:regenerate | () => void | - | Fires when the regenerate button is pressed. |
userLabel | string | You | Accessible name of user messages. |
assistantLabel | string | Assistant | Name shown above assistant messages and their accessible name, such as the product name. |
typingLabel | string | Typing | Hidden status text while typing is on. |
actionsLabel | string | Message actions | Accessible name of the action group. |
copyLabel | string | Copy | Accessible name of the copy button. |
copiedLabel | string | Copied | Status announced after copying. |
likeLabel | string | Good response | Accessible name of the like button. |
dislikeLabel | string | Bad response | Accessible name of the dislike button. |
regenerateLabel | string | Regenerate | Accessible name of the regenerate button. |
(feedback) / (regenerate) | output | - | Angular only. Emits the new rating (like, dislike, or null) and a press of regenerate. Svelte uses onFeedback and onRegenerate like React. |
markas-feedback / markas-regenerate | CustomEvent | - | Astro only. Bubbling events from markas-chat-message, with the new rating as detail for feedback. |
Accessibility
- Each message is an article named by userLabel or assistantLabel. Put the messages inside an element with role="log" so new ones are announced.
- The actions fade in on hover and on keyboard focus inside the message, and stay visible on touch screens. Like and dislike are toggle buttons with aria-pressed.
- Copying announces copiedLabel through a status region. The typing dots are hidden and announced as typingLabel.
- While streaming, screen readers get the full text at once from a hidden copy. Reduced motion skips the streaming and the pulsing.
Related components
More markasui components with the same classes in every framework.
- Bottom NavigationMobile app style bottom bar. A pill glides to the selected item, its label rises in, and the bar can shrink to icons while content scrolls.
- Card StackLayered stack of cards. Swipe, arrow keys, or buttons throw the top card away and the next one rises. Loops, with a position indicator.
- Currency InputMoney field that formats as you type (Rp 12.500.000), keeps the caret in place, and posts the plain number. Optional quick amount chips.
- DockmacOS style dock. Icons grow smoothly toward the pointer or focus, show a label above, mark open items with a dot, and bounce on launch.
- Drag ElementsArea of cards or stickers you can drag around with light momentum, kept inside its bounds. Arrow keys move a focused item, Escape puts it back.
- Dynamic IslandBlack pill inspired by the iPhone Dynamic Island. It morphs smoothly between idle, compact, and expanded states while its content crossfades.