# Surface

Shell giữ header, conversation viewport và composer trong một khung.

## 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/surface.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-surface .store=${fixtures.store()} viewer-type="customer">
    <strong slot="header">Store assistant</strong>
    <chatty-thread></chatty-thread>
    <chatty-composer slot="footer"></chatty-composer>
  </chatty-surface>`;
}
```

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/surface.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-surface
    .store=${fixtures.store()}
    viewer-type="agent"
    self-types='["agent","bot"]'
  >
    <strong slot="header">Store assistant</strong>
    <chatty-thread></chatty-thread>
    <chatty-composer slot="footer"></chatty-composer>
  </chatty-surface>`;
}
```


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.

Viewport mở tại đáy và theo tin mới. Khi shopper cuộn lên, giữ vị trí và hiện New messages; `.newMessagesLabel` dịch nhãn. Slot `empty` hiện khi store không có tin; `.renderMessage` truyền xuống thread.

Example (Standard) — Greeting trong slot empty của store rỗng.

```js
import '@avada/chatty-ui/tokens/tokens.css';
import {html} from 'lit';
import '@avada/chatty-ui/elements/surface.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 Empty() {
  return html`<chatty-surface .store=${fixtures.store([])} viewer-type="customer">
    <strong slot="header">Store assistant</strong>
    <div slot="empty">
      <h3>How can we help?</h3>
      <p>Ask about products, delivery or your order.</p>
    </div>
    <chatty-composer slot="footer"></chatty-composer>
  </chatty-surface>`;
}
```

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

```js
import '@avada/chatty-ui/tokens/admin.css';
import {html} from 'lit';
import '@avada/chatty-ui/elements/surface.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 EmptyAdmin() {
  return html`<chatty-surface
    .store=${fixtures.store([])}
    viewer-type="agent"
    self-types='["agent","bot"]'
  >
    <strong slot="header">Store assistant</strong>
    <div slot="empty">
      <h3>How can we help?</h3>
      <p>Ask about products, delivery or your order.</p>
    </div>
    <chatty-composer slot="footer"></chatty-composer>
  </chatty-surface>`;
}
```

### Element

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

### API

| Kind | Name | Type | Default | Description |
| --- | --- | --- | --- | --- |
| attribute | `label` | string | `'Conversation'` | Accessible conversation name. |
| attribute | `viewer-type` | string | `'customer'` | Sender type displayed on the trailing side. |
| attribute | `new-messages-label` | string | `'New messages'` | Translated action shown when updates arrive while reading older messages. |
| slot | default | Not available | Not available | Thread or other conversation content; defaults to a store-backed thread. |
| slot | `empty` | Not available | Not available | Greeting or empty state when the store has no messages. |
| slot | `header` | Not available | Not available | Persistent header. |
| slot | `footer` | Not available | Not available | Composer or contact step. |
| part | `base` | Not available | Not available | Surface shell. |
| part | `header` | Not available | Not available | Header wrapper. |
| part | `viewport` | Not available | Not available | Scrolling conversation viewport. |
| part | `new-messages` | Not available | Not available | Jump to the latest messages. |
| part | `footer` | Not available | Not available | Footer wrapper. |
| css-property | `--chatty-surface-height` | Not available | Not available | Shell height. |
| css-property | `--chatty-surface-footer-inset` | Not available | `0px` | Additional footer clearance. |
| attribute | `self-types` | Array<string> , null | `null` | Sender types on the trailing side; null falls back to viewerType. |

Đặt `--chatty-surface-footer-inset` trên surface để chừa khoảng trống cho composer khi bàn phím mở; mặc định `0px`.

## 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 store | Per-message subscriptions |

### 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 | Named conversation region | Native links and actions remain keyboard accessible | Not available | See neutral token preview |
| AI Mode | Named conversation region | Native links and actions remain keyboard accessible | Not available | See neutral token preview |
| Admin | Named conversation region | Native links and actions remain keyboard accessible | Not available | See neutral token preview |

