# Composer

Draft tin nhắn có attachment, gửi bằng Enter và event tới host.

## 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 |
| --- | --- |
| `Composer` | 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 Compose() {
  return (
    <Composer.Root onSubmit={() => {}}>
      <label htmlFor="current-message">Message</label>
      <Composer.Input>
        <textarea id="current-message" style={{fontSize: 16}} />
      </Composer.Input>
    </Composer.Root>
  );
}
```

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

`send(text)` gửi suggestion text; bỏ tham số để gửi draft hiện tại. Slot `toolbar` chứa action prefill hoặc gợi ý do host quản lý.

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/composer.js';
import '@avada/chatty-ui/elements/button.js';
export function Standard() {
  return html`<div
    @chatty-send=${(event) => {
      event.currentTarget.querySelector('[role=status]').textContent = `Sent: ${event.detail.text}`;
    }}
  >
    <chatty-composer>
      <chatty-button
        slot="toolbar"
        @click=${(event) => event.currentTarget.closest('chatty-composer').send('Track my order')}
        >Track my order</chatty-button
      >
    </chatty-composer>
    <p role="status"></p>
  </div>`;
}
```

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

Enter gửi, Shift+Enter xuống dòng; IME composition không gửi. Event `chatty-send` có `{text, attachments}`, bubbles và composed; preventDefault giữ draft. Form reset khôi phục value ban đầu. Input font đủ lớn cho iOS.

Textarea tự cao tối đa 5 dòng rồi cuộn. Send là icon button cùng hàng; click Send trả focus về textarea. `.sending` giữ draft, làm mờ và đặt aria-busy; host clear `.value` sau khi gửi thành công. `.disabled` dành cho trạng thái không cho tương tác.

### Element

| Element | Module |
| --- | --- |
| `chatty-composer` | @avada/chatty-ui/elements/composer.js |

### API

| Kind | Name | Type | Default | Description |
| --- | --- | --- | --- | --- |
| attribute | `value` | string | `''` | Draft text and form value. |
| attribute | `name` | string | `'message'` | Name used by the enclosing form. |
| attribute | `label` | string | `'Message'` | Accessible input label. |
| attribute | `send-label` | string | `'Send'` | Translated send button text. |
| attribute | `placeholder` | string | `'Write a message…'` | Optional draft hint. |
| attribute | `disabled` | boolean | `false` | Prevents edits and submission while pending. |
| attribute | `sending` | boolean | `false` | Host-owned send in progress; retains and dims the draft without dropping focus. |
| event | `chatty-send` | CustomEvent<{text: string, attachments: Array}> | Not available | Nonempty submission; cancel to retain the draft. |
| event | `click` | MouseEvent | Not available | Native send button click. |
| slot | `toolbar` | Not available | Not available | Suggestion and prefill actions before the typing row. |
| slot | `attachments` | Not available | Not available | Selected attachment previews. |
| part | `base` | Not available | Not available | Composer container. |
| part | `control` | Not available | Not available | Textarea. |
| part | `send` | Not available | Not available | Send button. |

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

Not available — React component tương ứng không có trong surface này; không dựng preview giả.

### Import / element

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| Not available | Not available | Not available |

### Anatomy

| Part | Element |
| --- | --- |
| 1 | Not available |

### Placement / order

| Context | Order |
| --- | --- |
| Conversation | Not available |

### Props

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| Not available | Not available | Not available | Not available | Not available |

### 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 |
| --- | --- | --- | --- |
| Not available | Not available | Not available | Not available |

### Behaviour

| Interaction | Result |
| --- | --- |
| Not available | Not available |

### Copy

| String | i18n key | Where |
| --- | --- | --- |
| Not available | Not available | Not available |

### Source

| File | Evidence |
| --- | --- |
|  | Owning React implementation shown in Current. |

## 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 | Named textarea | Enter send; Shift+Enter newline; IME retained | Not available | See neutral token preview |
| AI Mode | Named textarea | Enter send; Shift+Enter newline; IME retained | Not available | See neutral token preview |
| Admin | Named textarea | Enter send; Shift+Enter newline; IME retained | Not available | See neutral token preview |

