Chat Message
Pesan dalam percakapan AI. Gelembung user di kanan, balasan asisten dengan avatar, aksi saat hover, indikator mengetik, dan efek streaming token opsional.
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";
}Contoh
Chat dukungan dengan gelembung
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";
}Jawaban streaming
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";
}Transkrip hanya baca
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";
}Instalasi
npx markasui@latest add chat-messagepnpm dlx markasui@latest add chat-messageyarn dlx markasui@latest add chat-messagebunx --bun markasui@latest add chat-message- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Pasang dependensi:
npm install alpinejs - Salin source komponen di bawah ini ke
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>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
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>
);
}- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
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>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
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>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
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>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
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);
}
}Pemakaian
<div role="log" aria-label="Percakapan" class="grid gap-5">
<x-markas.chat-message from="user" text="Bagaimana menagih klien dalam Rupiah?" time="10.24" user-label="Anda" />
<x-markas.chat-message
text="Atur mata uang ke IDR dan tulis setiap item beserta nominalnya."
time="10.24"
assistant-label="Markas AI"
actions-label="Aksi pesan"
copy-label="Salin"
copied-label="Tersalin"
like-label="Jawaban bagus"
dislike-label="Jawaban buruk"
regenerate-label="Buat ulang"
/>
<x-markas.chat-message typing assistant-label="Markas AI" typing-label="Sedang mengetik" />
</div>import { ChatMessage } from "@/components/markas/ChatMessage";
<ChatMessage
text={jawaban}
assistantLabel="Markas AI"
copyLabel="Salin"
copiedLabel="Tersalin"
likeLabel="Jawaban bagus"
dislikeLabel="Jawaban buruk"
regenerateLabel="Buat ulang"
onFeedback={nilai}
/>;<script setup lang="ts">
import ChatMessage from "@/components/markas/ChatMessage.vue";
</script>
<template>
<ChatMessage
from="user"
text="Bagaimana menagih klien dalam Rupiah?"
user-label="Anda"
copy-label="Salin"
copied-label="Tersalin"
/>
</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>Custom element kecil menjalankan streaming, menyalin teks, dan mengganti rating. Ia mengirim markas-feedback (nilai baru sebagai detail) dan markas-regenerate, keduanya menggelembung.
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() {}
}- Baris aksi muncul saat kursor di atas pesan atau fokus ada di dalamnya, jadi percakapan tetap rapi.
- Copy menampilkan centang selama dua detik. Like dan dislike saling eksklusif dan memicu feedback dengan nilai barunya.
- stream memunculkan teks kata demi kata dengan kursor. Bila text bertambah saat streaming, kemunculan berlanjut sampai akhir yang baru.
- Reduced motion mematikan streaming, denyut titik, dan efek pudar.
Props
| Nama | Tipe | Default | Keterangan |
|---|---|---|---|
from | "user" | "assistant" | assistant | Penulis pesan. Pesan user berupa gelembung primary di kanan, pesan asisten di kiri dengan avatar. |
text | string | "" | Teks pesan. Baris baru dipertahankan. Copy menyalin teks ini ke clipboard. |
variant | "plain" | "bubble" | plain | Gaya asisten: teks polos, atau gelembung halus subtle. |
time | string | - | Waktu dalam elemen time, di samping nama untuk asisten dan di bawah gelembung untuk user. |
avatar | string | - | URL gambar avatar asisten. Tanpa ini tampil ikon kilau. |
typing | boolean | false | Menampilkan tiga titik berdenyut sebagai ganti teks, diumumkan sebagai typingLabel. |
stream | boolean | false | Memunculkan teks token demi token dengan kursor, seperti model yang streaming. Dengan reduced motion teks tampil utuh sekaligus. |
streamSpeed | number | 40 | Jeda antar token dalam ms. |
actions | boolean | true | Menampilkan baris aksi saat hover dan fokus: copy, plus like, dislike, dan regenerate untuk asisten. Disembunyikan saat mengetik atau streaming. |
onFeedback / @feedback / x-on:feedback | (value: "like" | "dislike" | null) => void | - | Dipicu saat like atau dislike diubah. Menekan yang aktif sekali lagi mengirim null. |
onRegenerate / @regenerate / x-on:regenerate | () => void | - | Dipicu saat tombol regenerate ditekan. |
userLabel | string | You | Nama aksesibel pesan user. Default "You", isi misalnya "Anda". |
assistantLabel | string | Assistant | Nama di atas pesan asisten sekaligus nama aksesibelnya, misalnya nama produk. Default "Assistant", isi misalnya "Asisten". |
typingLabel | string | Typing | Teks status tersembunyi saat typing aktif. Default "Typing", isi misalnya "Sedang mengetik". |
actionsLabel | string | Message actions | Nama aksesibel grup aksi. Default "Message actions", isi misalnya "Aksi pesan". |
copyLabel | string | Copy | Nama aksesibel tombol copy. Default "Copy", isi misalnya "Salin". |
copiedLabel | string | Copied | Status yang diumumkan setelah menyalin. Default "Copied", isi misalnya "Tersalin". |
likeLabel | string | Good response | Nama aksesibel tombol like. Default "Good response", isi misalnya "Jawaban bagus". |
dislikeLabel | string | Bad response | Nama aksesibel tombol dislike. Default "Bad response", isi misalnya "Jawaban buruk". |
regenerateLabel | string | Regenerate | Nama aksesibel tombol regenerate. Default "Regenerate", isi misalnya "Buat ulang". |
(feedback) / (regenerate) | output | - | Khusus Angular. Memancarkan rating baru (like, dislike, atau null) dan tekanan regenerate. Svelte memakai onFeedback dan onRegenerate seperti React. |
markas-feedback / markas-regenerate | CustomEvent | - | Khusus Astro. Event menggelembung dari markas-chat-message, dengan rating baru sebagai detail untuk feedback. |
Aksesibilitas
- Setiap pesan adalah article bernama userLabel atau assistantLabel. Letakkan pesan di dalam elemen role="log" agar pesan baru diumumkan.
- Aksi muncul saat hover dan saat fokus keyboard di dalam pesan, serta selalu tampil di layar sentuh. Like dan dislike adalah tombol toggle dengan aria-pressed.
- Menyalin mengumumkan copiedLabel lewat region status. Titik mengetik disembunyikan dan diumumkan sebagai typingLabel.
- Saat streaming, pembaca layar mendapat teks utuh sekaligus dari salinan tersembunyi. Reduced motion melewati streaming dan denyut.
Komponen terkait
Komponen markasui lain dengan class yang sama di setiap framework.
- Bottom NavigationBar bawah gaya aplikasi mobile. Pill meluncur ke item terpilih, labelnya muncul, dan bar bisa menciut jadi ikon saat konten discroll.
- Card StackTumpukan kartu bertingkat. Geser, tombol panah, atau tombol navigasi membuang kartu teratas lalu kartu berikutnya naik. Berputar, dengan indikator posisi.
- Currency InputKolom uang yang memformat saat mengetik (Rp 12.500.000), menjaga posisi kursor, dan mengirim angka murni. Opsional chip nominal cepat.
- DockDock ala macOS. Ikon membesar halus mengikuti kursor atau fokus, label muncul di atas, item terbuka bertitik, dan memantul saat dibuka.
- Drag ElementsArea kartu atau stiker yang bisa diseret dengan momentum ringan di dalam batasnya. Panah menggeser item yang fokus, Escape mengembalikannya.
- Dynamic IslandPill hitam terinspirasi Dynamic Island iPhone. Memuai mulus antara keadaan idle, compact, dan expanded sambil kontennya crossfade.