# 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.

- Category: MarkasUI
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/chat-message.json
- CLI: `npx markasui@latest add chat-message`

## When to use

Conversation views of AI assistants, chatbots, and support chats, together with PromptInput.

- Wrap the list of messages in role="log" with an aria-label
- Set assistantLabel to the assistant or product name
- Use typing until the first token arrives, then show the text
- Use stream only for a reveal effect, real streams can update text directly

## Code

### Blade

Save at `resources/views/components/markas/chat-message.blade.php`. Dependencies: alpinejs.

```blade
@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>
```

```blade
<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>
```

### React

Save at `src/components/markas/ChatMessage.tsx`. No extra dependencies.

```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>
  );
}
```

```tsx
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>;
```

### Vue

Save at `src/components/markas/ChatMessage.vue`. No extra dependencies.

```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>
```

```vue
<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>
```

### Svelte

Save at `src/lib/components/markas/ChatMessage.svelte`. No extra dependencies.

```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>
```

```svelte
<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>
```

### Astro

Save at `src/components/markas/ChatMessage.astro`. No extra dependencies.

```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>
```

```astro
---
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.

### Angular

Save at `src/app/markas/chat-message.component.ts`. No extra dependencies.

```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);
  }
}
```

```ts
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() {}
}
```

## 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.

## Notes

- 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.
