# Thread

Danh sách tin nhắn theo ID, ngăn cách theo ngày và chọn store slice.

## 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 |
| --- | --- |
| `CanonicalSurface` | 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 Surface() {
  return (
    <CanonicalSurface
      store={store}
      viewerType="agent"
      TextRenderer={Markdown}
      header={<strong>Conversation</strong>}
    />
  );
}
```

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/thread.js';
import '@avada/chatty-ui/elements/rating.js';
export const messages = [
  {
    id: 'question',
    senderType: 'customer',
    senderName: 'Customer',
    text: 'Which bag works for everyday trips?',
    status: 'sent',
    createdAt: '2026-01-15T10:00:00Z',
  },
  {
    id: 'answer',
    senderType: 'bot',
    senderName: 'Assistant',
    text: 'Try the **canvas tote**. It is lightweight and reusable.',
    status: 'sent',
    createdAt: '2026-01-15T10:01:00Z',
  },
  {
    id: 'detail',
    senderType: 'bot',
    senderName: 'Assistant',
    text: 'The wide straps make it comfortable to carry.',
    status: 'sent',
    createdAt: '2026-01-15T10:02:00Z',
    blocks: [{type: 'product', title: 'Canvas tote', price: '$24', image: 'https://chatty-ui-research.avada-tesla-chatty.workers.dev/fixtures/tote.svg'}],
  },
  {
    id: 'followup',
    senderType: 'customer',
    text: 'Does it come in other colors?',
    status: 'sent',
    createdAt: '2026-01-16T10:00:00Z',
  },
  {
    id: 'agent',
    senderType: 'agent',
    senderName: 'Alex',
    text: 'Yes, we also have navy and natural.',
    status: 'sent',
    createdAt: '2026-01-16T10:01:00Z',
  },
];
export const fixtures = {
  store: (items = messages) => {
    let state = {messages: items};
    const listeners = new Set();
    return {
      getState: () => state,
      subscribe(listener) {
        listeners.add(listener);
        return () => listeners.delete(listener);
      },
      setMessages(messages) {
        state = {messages};
        listeners.forEach((listener) => listener());
      },
    };
  },
};
export function Standard() {
  return html`<chatty-thread .store=${fixtures.store()} viewer-type="customer"></chatty-thread>`;
}
```

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/thread.js';
import '@avada/chatty-ui/elements/rating.js';
export const messages = [
  {
    id: 'question',
    senderType: 'customer',
    senderName: 'Customer',
    text: 'Which bag works for everyday trips?',
    status: 'sent',
    createdAt: '2026-01-15T10:00:00Z',
  },
  {
    id: 'answer',
    senderType: 'bot',
    senderName: 'Assistant',
    text: 'Try the **canvas tote**. It is lightweight and reusable.',
    status: 'sent',
    createdAt: '2026-01-15T10:01:00Z',
  },
  {
    id: 'detail',
    senderType: 'bot',
    senderName: 'Assistant',
    text: 'The wide straps make it comfortable to carry.',
    status: 'sent',
    createdAt: '2026-01-15T10:02:00Z',
    blocks: [{type: 'product', title: 'Canvas tote', price: '$24', image: 'https://chatty-ui-research.avada-tesla-chatty.workers.dev/fixtures/tote.svg'}],
  },
  {
    id: 'followup',
    senderType: 'customer',
    text: 'Does it come in other colors?',
    status: 'sent',
    createdAt: '2026-01-16T10:00:00Z',
  },
  {
    id: 'agent',
    senderType: 'agent',
    senderName: 'Alex',
    text: 'Yes, we also have navy and natural.',
    status: 'sent',
    createdAt: '2026-01-16T10:01:00Z',
  },
];
export const fixtures = {
  store: (items = messages) => {
    let state = {messages: items};
    const listeners = new Set();
    return {
      getState: () => state,
      subscribe(listener) {
        listeners.add(listener);
        return () => listeners.delete(listener);
      },
      setMessages(messages) {
        state = {messages};
        listeners.forEach((listener) => listener());
      },
    };
  },
};
export function StandardAdmin() {
  return html`<chatty-thread
    .store=${fixtures.store()}
    viewer-type="agent"
    self-types='["agent","bot"]'
  ></chatty-thread>`;
}
```


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 `.store` với `getState()` và `subscribe(listener)`; thread chọn danh sách ID/ngày, mỗi message chọn slice riêng. Host giữ reference các message chưa đổi; slot cho phép ghép UI trực tiếp khi chưa có store.

`.renderMessage(message)` trả object `{sender, badge, meta, actions}` chứa trusted Lit content; callback chạy trong row slice nên patch không render siblings. Chọn callback thay registry thứ hai để caller ghép rating/badge từ element có sẵn; không nhận HTML từ message.

Example (Standard) — Store-backed thread với rating trên bot reply.

```js
import '@avada/chatty-ui/tokens/tokens.css';
import {html} from 'lit';
import '@avada/chatty-ui/elements/thread.js';
import '@avada/chatty-ui/elements/rating.js';
export const messages = [
  {
    id: 'question',
    senderType: 'customer',
    senderName: 'Customer',
    text: 'Which bag works for everyday trips?',
    status: 'sent',
    createdAt: '2026-01-15T10:00:00Z',
  },
  {
    id: 'answer',
    senderType: 'bot',
    senderName: 'Assistant',
    text: 'Try the **canvas tote**. It is lightweight and reusable.',
    status: 'sent',
    createdAt: '2026-01-15T10:01:00Z',
  },
  {
    id: 'detail',
    senderType: 'bot',
    senderName: 'Assistant',
    text: 'The wide straps make it comfortable to carry.',
    status: 'sent',
    createdAt: '2026-01-15T10:02:00Z',
    blocks: [{type: 'product', title: 'Canvas tote', price: '$24', image: 'https://chatty-ui-research.avada-tesla-chatty.workers.dev/fixtures/tote.svg'}],
  },
  {
    id: 'followup',
    senderType: 'customer',
    text: 'Does it come in other colors?',
    status: 'sent',
    createdAt: '2026-01-16T10:00:00Z',
  },
  {
    id: 'agent',
    senderType: 'agent',
    senderName: 'Alex',
    text: 'Yes, we also have navy and natural.',
    status: 'sent',
    createdAt: '2026-01-16T10:01:00Z',
  },
];
export const fixtures = {
  store: (items = messages) => {
    let state = {messages: items};
    const listeners = new Set();
    return {
      getState: () => state,
      subscribe(listener) {
        listeners.add(listener);
        return () => listeners.delete(listener);
      },
      setMessages(messages) {
        state = {messages};
        listeners.forEach((listener) => listener());
      },
    };
  },
};
export function Feedback() {
  return html`<chatty-thread
    .store=${fixtures.store(messages.slice(0, 2))}
    viewer-type="customer"
    .renderMessage=${(message) =>
      message.senderType === 'bot'
        ? {
            actions: html`<chatty-rating label="Rate this answer"></chatty-rating>`,
            badge: html`<span>AI</span>`,
          }
        : {}}
  ></chatty-thread>`;
}
```

Example (Standard) — Admin dùng viewer agent.

```js
import '@avada/chatty-ui/tokens/admin.css';
import {html} from 'lit';
import '@avada/chatty-ui/elements/thread.js';
import '@avada/chatty-ui/elements/rating.js';
export const messages = [
  {
    id: 'question',
    senderType: 'customer',
    senderName: 'Customer',
    text: 'Which bag works for everyday trips?',
    status: 'sent',
    createdAt: '2026-01-15T10:00:00Z',
  },
  {
    id: 'answer',
    senderType: 'bot',
    senderName: 'Assistant',
    text: 'Try the **canvas tote**. It is lightweight and reusable.',
    status: 'sent',
    createdAt: '2026-01-15T10:01:00Z',
  },
  {
    id: 'detail',
    senderType: 'bot',
    senderName: 'Assistant',
    text: 'The wide straps make it comfortable to carry.',
    status: 'sent',
    createdAt: '2026-01-15T10:02:00Z',
    blocks: [{type: 'product', title: 'Canvas tote', price: '$24', image: 'https://chatty-ui-research.avada-tesla-chatty.workers.dev/fixtures/tote.svg'}],
  },
  {
    id: 'followup',
    senderType: 'customer',
    text: 'Does it come in other colors?',
    status: 'sent',
    createdAt: '2026-01-16T10:00:00Z',
  },
  {
    id: 'agent',
    senderType: 'agent',
    senderName: 'Alex',
    text: 'Yes, we also have navy and natural.',
    status: 'sent',
    createdAt: '2026-01-16T10:01:00Z',
  },
];
export const fixtures = {
  store: (items = messages) => {
    let state = {messages: items};
    const listeners = new Set();
    return {
      getState: () => state,
      subscribe(listener) {
        listeners.add(listener);
        return () => listeners.delete(listener);
      },
      setMessages(messages) {
        state = {messages};
        listeners.forEach((listener) => listener());
      },
    };
  },
};
export function FeedbackAdmin() {
  return html`<chatty-thread
    .store=${fixtures.store(messages.slice(0, 2))}
    viewer-type="agent"
    self-types='["agent","bot"]'
    .renderMessage=${(message) =>
      message.senderType === 'bot'
        ? {
            actions: html`<chatty-rating label="Rate this answer"></chatty-rating>`,
            badge: html`<span
              style="background:rgba(0,0,0,.06);border-radius:3px;padding:0 4px;color:var(--chatty-color-text-secondary)"
              >AI</span
            >`,
          }
        : {}}
  ></chatty-thread>`;
}
```

### Element

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

### API

| Kind | Name | Type | Default | Description |
| --- | --- | --- | --- | --- |
| attribute | `label` | string | `'Conversation'` | Accessible conversation name. |
| attribute | `viewer-type` | string | `'customer'` | Sender type on the trailing side. |
| attribute | `locale` | string | `'en'` | Locale used for calendar labels. |
| slot | default | Not available | Not available | Direct messages when no store is supplied. |
| part | `base` | Not available | Not available | Conversation log. |
| 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 |
| --- | --- | --- |
| `CanonicalSurface` | @avada/chatty-ui/canonical/Surface.jsx | CanonicalSurface |

### Anatomy

| Part | Element |
| --- | --- |
| 1 | CanonicalSurface |

### Placement / order

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

### Props

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| `store` | See source | Caller supplied | See source | Canonical runtime store |

### 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 messages | Keyed message rows |

### Copy

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

### 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 | Conversation log | Native links and actions remain keyboard accessible | Polite additions only | See neutral token preview |
| AI Mode | Conversation log | Native links and actions remain keyboard accessible | Polite additions only | See neutral token preview |
| Admin | Conversation log | Native links and actions remain keyboard accessible | Polite additions only | See neutral token preview |

