# Message

Khung tin nhắn canonical với nhóm sender, rich block và slot metadata.

## Key rules

- Element prototype là chuẩn để chatty-ui port theo.
- Host giữ dữ liệu, dịch nhãn và xử lý event; preview chỉ dùng dữ liệu cục bộ.

## Use when / Avoid

Dùng trong cuộc trò chuyện. Tránh nối trực tiếp element với API của shop.

### Use instead

| Component | Use when |
| --- | --- |
| `MessageFrame` | Implementation React đang chạy. |
| Element prototype | Consumer chuyển sang custom element. |

## Live preview

Example (Current (React), being replaced) — Component React thật; dữ liệu fixture, không gửi request.

```jsx
import React, {useState} from 'react';
import ChatThread from '@scripttag/v2/views/ChatThread.jsx';
import {chatStore} from '@scripttag/v2/stores/chatStore.js';
import {WidgetTextRenderer} from '@assets/pages/InboxManagement/v2/blocks/WidgetTextRenderer.jsx';
import {Markdown} from '@avada/chatty-ui/primitives/Markdown.js';
import {MessageFrame} from '@avada/chatty-ui/canonical/MessageFrame.jsx';
import {CanonicalSurface} from '@avada/chatty-ui/canonical/Surface.jsx';
import {PreChatPrompt} from '@avada/chatty-ui/canonical/PreChatPrompt.jsx';
import {Composer} from '@avada/chatty-ui/primitives/Composer.js';

const message = {
  id: 'guide-reply',
  senderType: 'bot',
  text: 'The **canvas tote** is lightweight.',
  status: 'sent',
  createdAt: '2026-11-23T10:00:00Z',
};
const store = {getState: () => ({messages: [message], loading: false}), subscribe: () => () => {}};

export function Message() {
  return (
    <MessageFrame vm={message} viewerType="customer" TextRenderer={Markdown} hideDayDividers />
  );
}
```

Example (Current (React), being replaced) — Classic reply renderer đang ship; dữ liệu fixture cục bộ.

```jsx
import React, {useState} from 'react';
import ChatThread from '@scripttag/v2/views/ChatThread.jsx';
import {chatStore} from '@scripttag/v2/stores/chatStore.js';
import {WidgetTextRenderer} from '@assets/pages/InboxManagement/v2/blocks/WidgetTextRenderer.jsx';
import {Markdown} from '@avada/chatty-ui/primitives/Markdown.js';
import {MessageFrame} from '@avada/chatty-ui/canonical/MessageFrame.jsx';
import {CanonicalSurface} from '@avada/chatty-ui/canonical/Surface.jsx';
import {PreChatPrompt} from '@avada/chatty-ui/canonical/PreChatPrompt.jsx';
import {Composer} from '@avada/chatty-ui/primitives/Composer.js';

const message = {
  id: 'guide-reply',
  senderType: 'bot',
  text: 'The **canvas tote** is lightweight.',
  status: 'sent',
  createdAt: '2026-11-23T10:00:00Z',
};
const store = {getState: () => ({messages: [message], loading: false}), subscribe: () => () => {}};

export function ClassicReply() {
  return (
    <WidgetTextRenderer
      text={message.text}
      format="markdown"
      vm={{...message, senderName: 'Assistant'}}
    />
  );
}
```

Example (Current (React), being replaced) — ChatThread V2 thật, cùng caller với waiting-streaming.

```jsx
import React, {useState} from 'react';
import ChatThread from '@scripttag/v2/views/ChatThread.jsx';
import {chatStore} from '@scripttag/v2/stores/chatStore.js';
import {WidgetTextRenderer} from '@assets/pages/InboxManagement/v2/blocks/WidgetTextRenderer.jsx';
import {Markdown} from '@avada/chatty-ui/primitives/Markdown.js';
import {MessageFrame} from '@avada/chatty-ui/canonical/MessageFrame.jsx';
import {CanonicalSurface} from '@avada/chatty-ui/canonical/Surface.jsx';
import {PreChatPrompt} from '@avada/chatty-ui/canonical/PreChatPrompt.jsx';
import {Composer} from '@avada/chatty-ui/primitives/Composer.js';

const message = {
  id: 'guide-reply',
  senderType: 'bot',
  text: 'The **canvas tote** is lightweight.',
  status: 'sent',
  createdAt: '2026-11-23T10:00:00Z',
};
const store = {getState: () => ({messages: [message], loading: false}), subscribe: () => () => {}};

export function StorefrontThread() {
  const [ready] = useState(() => {
    chatStore.setState({
      loadedId: 'guide-conversation',
      conversation: {id: 'guide-conversation'},
      awaitingReply: false,
      statusText: '',
      messages: [
        {
          id: 'question',
          senderType: 'customer',
          text: 'Which bag works for everyday trips?',
          blocks: [],
          createdAt: new Date('2026-01-15T10:00:00Z'),
        },
        {
          ...message,
          senderName: 'Assistant',
          createdAt: new Date('2026-01-15T10:01:00Z'),
          blocks: [],
        },
      ],
    });
    return true;
  });
  return ready ? (
    <div style={{height: 420, display: 'flex', flexDirection: 'column'}}>
      <ChatThread isActive navigate={false} />
    </div>
  ) : null;
}
```

## Standard

Example (Standard) — Element prototype với token trung tính.

```js
import '@avada/chatty-ui/tokens/tokens.css';
import {html} from 'lit';
import '@avada/chatty-ui/elements/message.js';
const message = {
  id: 'answer',
  senderType: 'bot',
  senderName: 'Assistant',
  text: 'Try the **canvas tote**. It is lightweight and reusable.',
  status: 'sent',
  createdAt: '2026-01-15T10:01:00Z',
};
export function Standard() {
  return html`<chatty-message .message=${message} viewer-type="customer"></chatty-message>`;
}
```

Example (Standard) — Standard: Admin viewer keeps customer messages on the leading side.

```js
import '@avada/chatty-ui/tokens/admin.css';
import {html} from 'lit';
import '@avada/chatty-ui/elements/message.js';
const message = {
  id: 'answer',
  senderType: 'bot',
  senderName: 'Assistant',
  text: 'Try the **canvas tote**. It is lightweight and reusable.',
  status: 'sent',
  createdAt: '2026-01-15T10:01:00Z',
};
export function StandardAdmin() {
  return html`<chatty-message
    .message=${message}
    viewer-type="agent"
    self-types='["agent","bot"]'
  ></chatty-message>`;
}
```


Admin chỉ dùng trong inbox và chỉ light; admin-dark là N/A.

`self-types` nhận JSON array, hoặc gán `.selfTypes`; `null` dùng `viewer-type`. Inbox truyền `["agent", "bot"]` để AI, Auto và agent cùng phía self; badge chỉ ghi nguồn gốc. Admin dùng tên sender cho cả nhãn và aria.

Gán property `.store` với `getState()` và `subscribe(listener)`; thay mảng messages theo immutable update và giữ reference các message chưa đổi. `.message`, `.prev`, `.next` hỗ trợ row độc lập. Thread dùng ID để giữ node khi prepend; group chỉ đổi khi sender, thời gian hoặc layout đổi.

Registry mặc định nhận product, products, suggestions, cart-confirmation, loading và reasoning; tin chỉ có type lạ được ẩn. Products giữ shape `{type:'products', data:{products, messageId}}`, nằm trước text và chiếm cả cột ở AI Mode. Registry nhận tag string hoặc `{tag, beforeText, wide}`. Suggestions phát `chatty-suggest` để host gọi composer `send(text)`; action Add to cart phát `chatty-add-to-cart`, host tự cập nhật store. Receipt dùng `data.receipts` (giữ đọc `receipt` hoặc `receipts` cũ) như React. `.registry` là registry riêng của consumer, map type sang tag tin cậy. `.message.blocks` giữ dữ liệu block; adapter product nhận title, price và image, rồi ghép product-card có sẵn.

Example (Standard) — Product block adapter dùng cùng product-card, không tự dựng card mới.

```html
<chatty-block-product
  block='{"title":"Canvas tote","price":"$24","image":"/fixtures/tote.svg"}'
></chatty-block-product>
```

Mặc định meta là giờ locale, full datetime ở time/title; chỉ pending/failed có status đã dịch qua `.strings`. Peer run đầu có sender. `layout=centered` dành cho activity không có bubble.

Example (Standard) — Activity row canh giữa: Agent joined.

```js
import '@avada/chatty-ui/tokens/tokens.css';
import {html} from 'lit';
import '@avada/chatty-ui/elements/message.js';
const message = {
  id: 'answer',
  senderType: 'bot',
  senderName: 'Assistant',
  text: 'Try the **canvas tote**. It is lightweight and reusable.',
  status: 'sent',
  createdAt: '2026-01-15T10:01:00Z',
};
export function Centered() {
  return html`<chatty-message
    .message=${{
      id: 'joined',
      senderType: 'system',
      layout: 'centered',
      text: 'Agent joined',
      createdAt: '2026-01-15T10:05:00Z',
    }}
  ></chatty-message>`;
}
```

### Element

| Element | Module |
| --- | --- |
| `chatty-message` | @avada/chatty-ui/elements/message.js |
| `chatty-block-product` | @avada/chatty-ui/elements/chatty-block-product.js |

### API

| Element | Kind | Name | Type | Default | Description |
| --- | --- | --- | --- | --- | --- |
| `chatty-message` | attribute | `message` | Object , null | `null` | Canonical message; keep untouched message references stable. |
| `chatty-message` | attribute | `message-id` | string | `''` | Stable ID selected from store.messages. |
| `chatty-message` | attribute | `viewer-type` | string | `'customer'` | Sender type displayed on the trailing side. |
| `chatty-message` | attribute | `surface` | string | `''` | Visual surface; inferred from the consumer theme root. |
| `chatty-message` | attribute | `locale` | string | `'en'` | Locale used for clocks and full datetimes. |
| `chatty-message` | slot | default | Not available | Not available | Additional block content. |
| `chatty-message` | slot | `sender` | Not available | Not available | Readable sender at the start of a run. |
| `chatty-message` | slot | `badge` | Not available | Not available | Sender badge. |
| `chatty-message` | slot | `meta` | Not available | Not available | Metadata after the message. |
| `chatty-message` | slot | `actions` | Not available | Not available | Message actions. |
| `chatty-message` | part | `base` | Not available | Not available | Message row. |
| `chatty-message` | part | `bubble` | Not available | Not available | Message text. |
| `chatty-message` | part | `blocks` | Not available | Not available | Rich blocks below the bubble. |
| `chatty-message` | part | `sender` | Not available | Not available | Sender label and badge. |
| `chatty-message` | part | `meta` | Not available | Not available | Metadata wrapper. |
| `chatty-message` | part | `actions` | Not available | Not available | Actions wrapper. |
| `chatty-message` | css-property | `--chatty-message-radius` | Not available | Not available | Bubble radius. |
| `chatty-block-product` | attribute | `block` | object | `{}` | Product block with title, price and optional image. |
| `chatty-block-product` | event | `chatty-open` | CustomEvent<{}> | Not available | Product activation forwarded by the card. |
| `chatty-block-product` | part | `base` | Not available | Not available | Product block container. |
| `chatty-message` | attribute | `self-types` | Array<string> , null | `null` | Sender types on the trailing side; null falls back to viewerType. |

## Classic

### Import / element

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| `WidgetTextRenderer` |  | WidgetTextRenderer |

### Anatomy

| Part | Element |
| --- | --- |
| 1 | Reply text and conversation rows |

### Placement / order

| Context | Order |
| --- | --- |
| Conversation | Customer question before bot reply |

### Props

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| Text / messages | Object | Caller supplied | See source | Fixture supplies local conversation |

### Sizes

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Bubble | Content | 8px 12px self; 7px 12px peer | 3px grouped; 14px runs | 18px; 6px tail | body-medium: 15px/22px desktop, 17px/24px mobile | Not available | 80% maximum; AI bot answer unboxed |

### Tokens

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Text | `--chatty-color-text` | Theme text | Theme text |

### States

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| New reply | Store update | Appended row | Conversation log |

### Behaviour

| Interaction | Result |
| --- | --- |
| Render | Shared widget implementation, frozen local fixture |

### Copy

| String | i18n key | Where |
| --- | --- | --- |
| Caller supplied | Not available | Message text |

### Source

| File | Evidence |
| --- | --- |
|  | Shipping storefront renderer used in Current preview. |

## AI Mode

### Import / element

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| `ChatThread` | import ChatThread from '@scripttag/v2/views/ChatThread.jsx'; | ChatThread |

### Anatomy

| Part | Element |
| --- | --- |
| 1 | Reply text and conversation rows |

### Placement / order

| Context | Order |
| --- | --- |
| Conversation | Customer question before bot reply |

### Props

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| Text / messages | Object | Caller supplied | See source | Fixture supplies local conversation |

### Sizes

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Bubble | Content | 10px 15px | 3px grouped; 14px runs | 18px; 6px tail | body-medium: 15px/22px desktop, 17px/24px mobile | Not available | 80% maximum; AI bot answer unboxed |

### Tokens

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Text | `--chatty-color-text` | Theme text | Theme text |

### States

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| New reply | Store update | Appended row | Conversation log |

### Behaviour

| Interaction | Result |
| --- | --- |
| Render | Shared widget implementation, frozen local fixture |

### Copy

| String | i18n key | Where |
| --- | --- | --- |
| Caller supplied | Not available | Message text |

### Source

| File | Evidence |
| --- | --- |
|  | Shipping storefront renderer used in Current preview. |

## Admin

### Import / element

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| `MessageFrame` | @avada/chatty-ui/canonical/MessageFrame.jsx | MessageFrame |

### Anatomy

| Part | Element |
| --- | --- |
| 1 | MessageFrame |

### Placement / order

| Context | Order |
| --- | --- |
| Conversation | Caller supplies surrounding content |

### Props

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| `vm` | See source | Caller supplied | See source | Canonical message |

### Sizes

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Not available | Not available | Not available | Not available | Not available | Not available | Not available | Not available |

### Tokens

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Not available | Not available | Not available | Not available |

### States

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| Rendered | Props supplied | See source | Not available |

### Behaviour

| Interaction | Result |
| --- | --- |
| Patch vm | Renders sender, text and blocks |

### Copy

| String | i18n key | Where |
| --- | --- | --- |
| Caller translated | Not available | MessageFrame |

### Source

| File | Evidence |
| --- | --- |
|  | Owning React implementation. |

## Do / Don't

Do: giữ host làm owner của dữ liệu.

Don't: gửi lại chỉ vì element render.

## Accessibility

| Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio |
| --- | --- | --- | --- | --- |
| Classic | Native content semantics | Native links and actions remain keyboard accessible | Not available | See neutral token preview |
| AI Mode | Native content semantics | Native links and actions remain keyboard accessible | Not available | See neutral token preview |
| Admin | Native content semantics | Native links and actions remain keyboard accessible | Not available | See neutral token preview |

