# Contact / email form

Thu email, tên và số điện thoại trong nhóm field ngay tại composer, với validation và trạng thái pending.

## Key rules

- Classic: dùng `ContactComposer` qua PreChatMsg; các field cùng hiện theo thứ tự email, name, phone.
- AI Mode: dùng cùng `ContactComposer` qua ChatPreForm; token màu đọc ở bảng Tokens của AI Mode.
- Lỗi validation hiện ngay dưới field và giá trị đang nhập vẫn do caller giữ.
- Classic: nút gửi cao 44px; field cao tối thiểu 52px.
- AI Mode: nút gửi cao 44px; field cao tối thiểu 52px.

## Use when / Avoid

Dùng form này khi cần thu thông tin liên hệ ngay trong luồng chat với các field được bật cùng hiển thị. Form nhiều field cho ca ngoài giờ hoặc bàn giao có component riêng, xem [Offline / after hours](https://chatty-ui-research.avada-tesla-chatty.workers.dev/patterns/offline-after-hours/) và [Handoff to a human](https://chatty-ui-research.avada-tesla-chatty.workers.dev/patterns/handoff-to-a-human/).

### Use instead

| Component | Use when |
| --- | --- |
| `ContactComposer` | Thu email, tên hoặc số điện thoại trong nhóm field tại composer slot. |
| `OfflineForm` | Classic ngoài giờ cần tên, email và nội dung trong một form. |
| `HandoverContactForm` | Classic cần form liên hệ khi bàn giao cho nhân viên. |

## Entry points

| Surface | Owner |
| --- | --- |
| Classic | `ContactComposer` qua PreChatMsg khi prop composer bật |
| AI Mode | `ContactComposer` qua ChatPreForm |

## Flow

| Surface | Step | Trigger | UI shown | Component | Copy + i18n key | Timing |
| --- | --- | --- | --- | --- | --- | --- |
| Classic | Nhập | Gõ vào field | Các field được bật cùng hiển thị; nút gửi nằm ở field cuối | `ContactComposer` | Email address / Email address | Tức thì |
| Classic | Lỗi | Submit không hợp lệ | Viền lỗi và dòng lỗi dưới field | `ContactComposer` | Email is invalid / Email is invalid | Tức thì khi submit |
| Classic | Gửi | Bước cuối hợp lệ | Nút gửi chuyển sang pending cho tới khi caller xử lý xong | `ContactComposer` | Send message / Send message | Theo vòng đời async của caller |
| Classic | Bỏ qua | Bấm nút bỏ qua hoặc Escape | Nhãn nút đổi sang Loading cho tới khi onSkip xong | `ContactComposer` | Chat anonymously / Chat anonymously | Theo vòng đời async của caller |
| AI Mode | Nhập | Gõ vào field | Các field được bật cùng hiển thị; nút gửi nằm ở field cuối | `ContactComposer` | Email address / Email address | Tức thì |
| AI Mode | Lỗi | Submit không hợp lệ | Viền lỗi và dòng lỗi dưới field | `ContactComposer` | Email is invalid / Email is invalid | Tức thì khi submit |
| AI Mode | Gửi | Bước cuối hợp lệ | Nút gửi chuyển sang pending cho tới khi caller xử lý xong | `ContactComposer` | Send message / Send message | Theo vòng đời async của caller |
| AI Mode | Bỏ qua | Bấm nút bỏ qua hoặc Escape | Nhãn nút đổi sang Loading cho tới khi onSkip xong | `ContactComposer` | Chat anonymously / Chat anonymously | Theo vòng đời async của caller |

## Edge cases

| Surface | Case | Behaviour |
| --- | --- | --- |
| Classic | Field bắt buộc để trống | Hiện lỗi theo field, focus field lỗi đầu tiên và giữ giá trị |
| Classic | Email sai dạng | Hiện lỗi Email is invalid |
| Classic | Phone sai dạng hoặc ngoài khoảng chữ số | Hiện lỗi Phone number is invalid |
| Classic | Nhấn gửi khi một field không hợp lệ | Focus field không hợp lệ đầu tiên và hiện lỗi của field đó |
| Classic | Bấm gửi hoặc bỏ qua khi đang xử lý | Bỏ qua lần gọi thứ hai |
| AI Mode | Field bắt buộc để trống | Hiện lỗi theo field, focus field lỗi đầu tiên và giữ giá trị |
| AI Mode | Email sai dạng | Hiện lỗi Email is invalid |
| AI Mode | Phone sai dạng hoặc ngoài khoảng chữ số | Hiện lỗi Phone number is invalid |
| AI Mode | Nhấn gửi khi một field không hợp lệ | Focus field không hợp lệ đầu tiên và hiện lỗi của field đó |
| AI Mode | Bấm gửi hoặc bỏ qua khi đang xử lý | Bỏ qua lần gọi thứ hai |

## Live preview

Classic: bubble thu gọn là fixture từ chatty-icon-button; Current: FloatButtonWidget, chưa có element. Bag và menu (…) ở header: N/A trong preview.

AI Mode: SignIn, EmailContinue, Reset và Bag ở header: N/A trong preview.

### Standard

Example (Standard) — Widget thread Standard; tương tác bằng dữ liệu fixture.

```js
import '@avada/chatty-ui/tokens/tokens.css';
import {html} from 'lit';
import {IconClose, IconMessage} from '@avada/chatty-ui/elements/icon-glyphs.js';
import '@avada/chatty-ui/elements/surface.js';
import '@avada/chatty-ui/elements/avatar.js';
import '@avada/chatty-ui/elements/badge.js';
import '@avada/chatty-ui/elements/icon-button.js';
import '@avada/chatty-ui/elements/launcher.js';
import '@avada/chatty-ui/elements/button.js';
import {sameGroup} from '@avada/chatty-ui/behaviors/messages.js';

// Reference viewport: 1280 × 900 desktop, 390 × 900 mobile.
const sizes = {
  classic: {width: 400, height: 700},
  'ai-mode': {width: 820, height: 657},
  admin: {width: 527, height: 842}
};
const question = {
  id: 'question',
  senderType: 'customer',
  text: 'Can you help me?',
  createdAt: '2026-01-15T10:00:00Z'
};

/** Viewport-relative sizing survives the initial hidden iframe layout. */
function widgetSize(surface) {
  const mode = new URLSearchParams(location.search).get('mobile');
  const isMobile = mode === null ? innerWidth < 900 : mode === 'true';
  const width = `min(${sizes[surface].width}px, max(0px, 100vw - 40px))`;
  const height = isMobile
    ? `min(${surface === 'admin' ? 848 : 888}px, round(down, calc(${width} * 2.2), 1px))`
    : `${sizes[surface].height}px`;
  return {...sizes[surface], height, mobile: isMobile};
}

/** Local immutable message state with real subscriptions for live previews. */
function fixtureStore(initial) {
  let state = {messages: initial};
  const listeners = new Set();
  return {
    getState: () => state,
    subscribe(listener) {
      listeners.add(listener);
      return () => listeners.delete(listener);
    },
    setMessages(messages) {
      state = {messages};
      listeners.forEach(listener => listener());
    }
  };
}

/** Appends the viewer message without replacing the existing conversation. */
function appendViewer(store, surface, text) {
  const message = {
    id: `viewer-${store.getState().messages.length}`,
    senderType: surface === 'admin' ? 'agent' : 'customer',
    senderMeta: {name: surface === 'admin' ? 'Alex' : 'You'},
    text,
    createdAt: new Date().toISOString()
  };
  store.setMessages([...store.getState().messages, message]);
}

/**
 * One shell owns surface sizing, header, thread and composer for every pattern.
 * @param {string} surface
 * @param {Object} store
 * @param {Object} strings
 * @param {Object} content
 * @param {Function} renderMessage
 * @param {Function} onSend
 * @param {Object} registry
 * @param {boolean} composerHidden
 * @param {string} title
 * @param {Object} headerStart
 * @param {Object} headerActions
 * @param {boolean} sheet
 * @param {string | null} status
 * @returns {Object}
 */
function patternShell({
  surface,
  store,
  strings = {header: 'Store assistant', message: 'Message', send: 'Send'},
  content,
  renderMessage,
  onSend,
  registry,
  title,
  headerStart,
  headerActions,
  status = 'online',
  sheet = false,
  composerHidden = false
}) {
  const size = widgetSize(surface);
  const mobileSheet = sheet && size.mobile;
  if (mobileSheet) {
    size.width = 'none';
    size.height = 'calc(100dvh - 12px)';
  }
  const toggle = (event, closed) => {
    const frame = event.currentTarget.closest('[data-pattern-frame]');
    const panel = frame.querySelector('chatty-surface');
    const launcher = frame.querySelector('[data-pattern-launcher]');
    panel.hidden = closed;
    frame.dataset.closed = String(closed);
    const background = frame.querySelector('[data-sheet-page]');
    if (background) background.inert = !closed && surface === 'ai-mode';
    launcher.hidden = !closed;
    if (closed) {
      launcher.style.insetBlockEnd = `${Math.max(surface === 'ai-mode' ? 40 : 16, frame.getBoundingClientRect().bottom - innerHeight + 20)}px`;
      launcher.focus({preventScroll: true});
    } else {
      const composer = panel.querySelector('chatty-composer');
      const input = !composer.hidden
        ? composer.renderRoot.querySelector('textarea')
        : (panel
            .querySelector('chatty-contact-form:not([hidden])')
            ?.renderRoot.querySelector('chatty-text-field') ??
          panel.querySelector('form chatty-text-field') ??
          panel.querySelector('[data-welcome-invitation]:not([hidden]) chatty-button') ??
          panel
            .querySelector('chatty-pre-chat:not([hidden])')
            ?.renderRoot.querySelector('chatty-button'));
      input?.focus({preventScroll: true});
    }
  };
  const sender = message => {
    const content = renderMessage?.(message) ?? {};
    const messages = store.getState().messages;
    const previous = messages[messages.indexOf(message) - 1];
    if (message.senderType !== 'bot' || sameGroup(message, previous)) return content;
    return {
      ...content,
      sender: html`<span style="display:inline-flex;align-items:center;gap:6px"
        ><chatty-avatar size="sm" label="Assistant">A</chatty-avatar
        >${content.sender ?? message.senderName ?? message.senderMeta?.name ?? 'Assistant'}</span
      >`
    };
  };
  return html`<style>
      [data-pattern-frame] {
        display: flex;
        position: relative;
        justify-content: center;
        inline-size: 100%;
        min-inline-size: 0;
      }
      [data-pattern-frame='classic'] {
        justify-content: flex-end;
      }
      [data-pattern-frame] chatty-surface::part(header) {
        padding: 0;
      }
      [data-pattern-frame='classic'] chatty-surface::part(header),
      [data-pattern-frame='ai-mode'] chatty-surface::part(header) {
        border-bottom-width: 0;
      }
      [data-pattern-frame] [hidden] {
        display: none !important;
      }
      [data-pattern-header] {
        display: flex;
        align-items: center;
        gap: 10px;
        box-sizing: border-box;
        min-inline-size: 0;
        block-size: 52px;
        padding: 0 16px;
      }
      [data-pattern-frame='classic'] [data-pattern-header] {
        block-size: 56px;
        background: var(--chatty-color-accent);
        color: var(--chatty-color-on-accent);
      }
      [data-pattern-frame='classic'] [data-pattern-header] chatty-icon-button {
        --chatty-color-border-focus: var(--chatty-color-on-accent);
      }
      [data-pattern-frame='admin'] [data-pattern-header] {
        block-size: 68px;
        padding: 8px 12px;
      }
      [data-pattern-header] chatty-avatar {
        --chatty-avatar-size: 32px;
      }
      [data-pattern-frame='classic'] [data-pattern-header] chatty-avatar {
        --chatty-avatar-background: #fff;
      }
      [data-pattern-frame='classic'] [data-pattern-header] chatty-avatar::part(base) {
        color: #303030;
        border: 1px solid #767676;
      }
      [data-pattern-actions] {
        display: flex;
        align-items: center;
        gap: 8px;
      }
      [data-pattern-title] {
        flex: 1;
        min-inline-size: 0;
        display: flex;
        flex-direction: column;
      }
      [data-pattern-frame='admin'] [data-pattern-title] {
        gap: 4px;
      }
      [data-pattern-frame='admin'] [data-pattern-title] strong {
        display: flex;
        align-items: center;
        min-block-size: 28px;
        font: var(--p-font-weight-semibold, 650) var(--p-text-heading-md-font-size, 14px) /
          var(--p-text-heading-md-font-line-height, 20px) var(--p-font-family-sans, system-ui);
      }
      [data-pattern-title] strong {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      [data-pattern-header] chatty-icon-button {
        --chatty-icon-button-size: 32px;
        --chatty-icon-button-color: currentColor;
      }
      @media (max-width: 899px), (pointer: coarse) {
        [data-pattern-header] chatty-icon-button {
          --chatty-icon-button-size: 44px;
        }
      }
      [data-pattern-launcher] {
        position: absolute;
        inset-inline-end: 0;
        inset-block-end: 0;
      }
      [data-pattern-frame='ai-mode'] [data-pattern-launcher] {
        inset-inline-end: auto;
        inset-inline-start: 50%;
        transform: translateX(-50%);
      }
      [data-pattern-frame='classic'] [data-pattern-launcher] {
        --chatty-icon-button-size: 56px;
        border-radius: 50%;
        background: var(--chatty-color-accent);
        --chatty-icon-button-color: var(--chatty-color-on-accent);
      }
      [data-sheet-mobile='true'] {
        position: fixed;
        inset: 0;
        inline-size: 100vw;
      }
      [data-sheet-mobile='true'] chatty-surface::part(base) {
        border-radius: 16px 16px 0 0;
      }
      [data-sheet-mobile='true'] chatty-surface {
        position: relative;
        z-index: 2;
        margin-block-start: 12px;
      }
      [data-sheet-page],
      [data-sheet-scrim] {
        position: absolute;
        inset: 0;
        box-sizing: border-box;
      }
      [data-sheet-page] {
        padding: 20px;
        background: var(--chatty-color-bg-surface);
        color: var(--chatty-color-text);
      }
      [data-sheet-scrim] {
        z-index: 1;
        border: 0;
        background: rgb(0 0 0 / 40%);
        animation: sheet-scrim 400ms ease;
      }
      [data-sheet-mobile='true'][data-closed='true'] [data-sheet-scrim] {
        display: none;
      }
      [data-sheet-mobile='true'] [data-pattern-launcher] {
        z-index: 3;
      }
      @keyframes sheet-scrim {
        from {
          opacity: 0;
        }
        to {
          opacity: 1;
        }
      }
      @media (prefers-reduced-motion: reduce) {
        [data-sheet-scrim] {
          animation: none;
        }
      }
    </style>
    <div
      data-pattern-frame=${surface}
      data-sheet-mobile=${String(mobileSheet)}
      data-closed="false"
      style=${`block-size:calc(${size.height} + ${mobileSheet ? 12 : 0}px)`}
    >
      ${
        mobileSheet
          ? html`<div data-sheet-page .inert=${surface === 'ai-mode'}>
                <p>Example storefront</p>
                <chatty-button
                  variant="secondary"
                  type="button"
                  @click=${event => {
                    event.currentTarget.textContent = 'Products opened';
                  }}
                >
                  Browse products
                </chatty-button>
              </div>
              ${surface === 'ai-mode' ? html`<button type="button" data-sheet-scrim tabindex="-1" aria-label="Close chat background" @click=${event => toggle(event, true)}></button>` : ''}`
          : ''
      }
      <chatty-surface
        data-chatty-surface=${surface}
        data-chatty-theme=${surface === 'admin' ? 'light' : (document.documentElement.dataset.chattyTheme ?? document.documentElement.dataset.theme ?? 'light')}
        style=${`inline-size:100%;max-inline-size:${mobileSheet ? 'none' : `${size.width}px`};--chatty-surface-height:${size.height}`}
        .store=${store}
        .registry=${registry ?? null}
        viewer-type=${surface === 'admin' ? 'agent' : 'customer'}
        .selfTypes=${surface === 'admin' ? ['agent', 'bot'] : null}
        .renderMessage=${sender}
      >
        <div slot="header" data-pattern-header>
          ${headerStart ?? ''}
          ${surface === 'admin' ? '' : html`<chatty-avatar label="Store" .status=${status}>S</chatty-avatar>`}
          <span data-pattern-title
            ><strong
              >${title ?? (surface === 'admin' ? 'Customer conversation' : strings.header)}</strong
            >${surface === 'admin' ? html`<chatty-badge size="sm" variant="secondary" style="align-self:flex-start">Customer</chatty-badge>` : status == null ? '' : html`<small data-pattern-status>${status === 'online' ? 'Open' : 'Closed'}</small>`}</span
          >
          <span data-pattern-actions>${headerActions ?? ''}</span>
          ${
            surface === 'admin'
              ? ''
              : html`<chatty-icon-button label="Close panel" @click=${event => toggle(event, true)}
                  >${IconClose()}</chatty-icon-button
                >`
          }
        </div>
        <chatty-thread .strings=${{bot: 'Assistant', ...strings}}></chatty-thread>${content ?? ''}
        <chatty-composer
          slot="footer"
          ?hidden=${composerHidden}
          .label=${strings.message}
          .sendLabel=${strings.send}
          @chatty-send=${event => {
            appendViewer(store, surface, event.detail.text);
            if (onSend) onSend(event.detail.text, event.currentTarget);
            else if (surface !== 'admin')
              store.setMessages([
                ...store.getState().messages,
                {
                  id: `fixture-${store.getState().messages.length}`,
                  senderType: 'bot',
                  text: `You asked: “${event.detail.text}”. I can help with that.`,
                  hasEventTime: false
                }
              ]);
          }}
        ></chatty-composer> </chatty-surface
      >${
        surface === 'admin'
          ? ''
          : surface === 'ai-mode'
            ? html`<chatty-launcher
                data-pattern-launcher
                hidden
                label="Open chat"
                @chatty-open=${event => toggle(event, false)}
                >${IconMessage({size: 20, slot: 'icon'})}Ask a question</chatty-launcher
              >`
            : html`<chatty-icon-button
                data-pattern-launcher
                hidden
                size="lg"
                label="Open chat"
                @click=${event => toggle(event, false)}
                >${IconMessage({size: 24})}</chatty-icon-button
              >`
      }
    </div>`;
}

import '@avada/chatty-ui/elements/contact-form.js';
export function Standard({surface}) {
  const store = fixtureStore([question]);
  const fields = [
    {
      key: 'email',
      type: 'email',
      label: 'Email address',
      placeholder: 'you@example.com',
      required: true
    },
    {key: 'name', label: 'Name', required: true},
    {key: 'phone', type: 'tel', label: 'Phone number'}
  ];
  const complete = (event, skipped = false) => {
    const form = event.currentTarget;
    if (skipped) form.skipping = true;
    else form.loading = true;
    const finish = () => {
      const container = form.parentElement;
      form.remove();
      const status = document.createElement('p');
      status.role = 'status';
      status.tabIndex = -1;
      status.textContent = skipped ? 'Anonymous chat ready' : 'Contact details saved';
      container.append(status);
      const composer = container.closest('chatty-surface').querySelector('chatty-composer');
      composer.hidden = false;
      status.focus();
    };
    if (matchMedia('(prefers-reduced-motion: reduce)').matches) finish();
    else setTimeout(finish, 450);
  };
  return patternShell({
    surface,
    store,
    composerHidden: true,
    content: html`<div slot="footer">
      <chatty-contact-form
        .fields=${fields}
        skippable
        .strings=${{submit: 'Send message', skip: 'Chat anonymously', loading: 'Loading', invalidEmail: 'Email is invalid', requiredField: 'Complete this field.', requiredEmail: 'Enter your email address.', requiredName: 'Enter your name.', invalidPhone: 'Phone number is invalid'}}
        @chatty-submit=${event => complete(event)}
        @chatty-skip=${event => complete(event, true)}
      ></chatty-contact-form>
    </div>`
  });
}
```

Submit và Escape/Chat anonymously dùng request fixture; giữ lịch sử. Contact fields cùng hiển thị tại footer thay composer cho đến khi hoàn tất; không lưu contact thật.

### Current

Example (Current (React), being replaced) — API ContactComposer của Classic với dữ liệu cục bộ; không gửi dữ liệu ra ngoài.

```jsx
import React, {useState} from 'react';
import {ContactComposer} from '@avada/chatty-ui/canonical/ContactComposer.jsx';

export function Form() {
  const [values, setValues] = useState({email: '', firstName: '', phone: ''});
  const [status, setStatus] = useState('');
  return (
    <div>
      <ContactComposer
        fields={['email', 'name', 'phone']}
        values={values}
        required={{email: true}}
        t={text => text}
        description="Where can we reply?"
        privacy="Your email is used to reply to this conversation."
        autoFocus={false}
        onChange={(key, value) => setValues(previous => ({...previous, [key]: value}))}
        onSubmit={() => setStatus('Contact details validated locally. No message was sent.')}
        onSkip={() => setStatus('Anonymous chat selected locally.')}
      />
      <p role="status">{status}</p>
    </div>
  );
}
```

Example (Current (React), being replaced) — API ContactComposer của AI Mode với dữ liệu cục bộ; không gửi dữ liệu ra ngoài.

```jsx
import React, {useState} from 'react';
import {ContactComposer} from '@avada/chatty-ui/canonical/ContactComposer.jsx';

export function Form() {
  const [values, setValues] = useState({email: '', firstName: '', phone: ''});
  const [status, setStatus] = useState('');
  return (
    <div>
      <ContactComposer
        fields={['email', 'name', 'phone']}
        values={values}
        required={{email: true}}
        t={text => text}
        description="Where can we reply?"
        privacy="Your email is used to reply to this conversation."
        autoFocus={false}
        onChange={(key, value) => setValues(previous => ({...previous, [key]: value}))}
        onSubmit={() => setStatus('Contact details validated locally. No message was sent.')}
        onSkip={() => setStatus('Anonymous chat selected locally.')}
      />
      <p role="status">{status}</p>
    </div>
  );
}
```

## Classic

### Import / element

#### ContactComposer

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| `ContactComposer` | @avada/chatty-ui/canonical/ContactComposer.jsx | .Avada-Faqs_Popup; Dark qua [data-theme] của popup |

### Anatomy

#### ContactComposer

| Part | Element |
| --- | --- |
| 1 | Mô tả tùy chọn trong `chatty-contact-description`; field email dùng nó làm aria-labelledby. |
| 2 | Nút bỏ qua trong `chatty-contact-skip`, chỉ render khi có `onSkip`. |
| 3 | Nhóm `chatty-contact-card` chứa các field: icon và input; field cuối có nút gửi. |
| 4 | Dòng lỗi trong `chatty-contact-error` với role alert. |
| 5 | Đồng ý bản tin khi có `newsletter`, rồi dòng privacy trong `chatty-contact-consent`. |

### Placement / order

#### ContactComposer

| Context | Order |
| --- | --- |
| Bên trong component | Mô tả, nút bỏ qua, nhóm field (icon, input; gửi ở field cuối), lỗi, đồng ý bản tin, privacy. |
| Caller Classic | PreChatMsg render ContactComposer khi prop composer bật; caller truyền fields, values, required, description, privacy. |

### Props

#### ContactComposer

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| `fields` | string[] | email, name, phone | email | Lọc theo thứ tự cố định; danh sách rỗng quay về email. |
| `required` | object | Cờ bắt buộc theo field | `{}` | Merchant đặt cờ cho từng field. |
| `description` | string | Do caller đặt | None | Render trong `chatty-contact-description`. |
| `privacy` | JSX.Element | Do caller đặt | None | Render trong `chatty-contact-consent` ở cuối. |
| `onSkip` | Function | Do caller đặt | None | Có giá trị mới hiện nút bỏ qua; Escape trong input cũng gọi. |
| `loading` | boolean | true / false | None | Cùng với skip đang chạy tạo trạng thái pending: disable field và nút, aria-busy. |
| `autoFocus` | boolean | true / false | `true` | autoFocus mặc định chỉ focus khi cửa sổ rộng hơn 899; focusRequest hoặc focusOnMount có thể focus trên mobile. |
| `inForm` | boolean | true / false | `false` | true: Root là div và nút gửi gọi submit qua onClick. |

### Sizes

#### ContactComposer

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Root | Theo nội dung | 8px 12px 12px | Không khai báo | Không khai báo | Kế thừa font của caller | Không áp dụng | Không có override theo viewport |
| Field | min-height 52px | 6px 9px 6px 14px | 10px | 28px | input-value Derived(15px = type(input-value, desktop, size)) / Derived(22px = type(input-value, desktop, line)) desktop → Derived(18px = type(input-value, mobile, size)) / Derived(24px = type(input-value, mobile, line)) mobile | Field cao tối thiểu 52px | JS .mobile khi mobileMaxWidth 899px |
| Grouped fields | min-height 44px mỗi field | 0 6px 0 12px | 8px | Card 18px; field 17px | input-value | 44px mỗi input | Khi có nhiều field |
| Submit | 44px | 0 | Không khai báo | 50% | Icon 16px | 44px | Không có override theo viewport |
| Skip button | min-height 44px | 12px | 6px | 999px | button-label Derived(14px = type(button-label, desktop, size)) / Derived(18px = type(button-label, desktop, line)) desktop → Derived(17px = type(button-label, mobile, size)) / Derived(24px = type(button-label, mobile, line)) mobile | 44px | JS .mobile khi mobileMaxWidth 899px |
| Error, consent | Theo nội dung | Error 6px 2px 0 | 6px | Không khai báo | body-small Derived(14px = type(body-small, desktop, size)) / Derived(20px = type(body-small, desktop, line)) desktop → Derived(15px = type(body-small, mobile, size)) / Derived(22px = type(body-small, mobile, line)) mobile | Không tương tác | JS .mobile khi mobileMaxWidth 899px |

### Tokens

#### ContactComposer

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Chữ và viền field | `--chatty-contact-fg` | #1f1f1f | #ececec |
| Nền field | `--chatty-contact-bg` | #f2f2f2 | #262626 |
| Chữ phụ | `--chatty-contact-muted` | #6b6b6b | #a3a3a3 |
| Placeholder | `--chatty-contact-placeholder` | #6b6b6b | #8d8d8d |
| Nền nút bỏ qua | `--chatty-contact-chip` | #fff | #1c1c1c |
| Viền nút bỏ qua | `--chatty-contact-line` | #e3e3e3 | #2e2e2e |
| Lỗi | `--chatty-contact-error` | #c4320a | #ff8a65 |

### States

#### ContactComposer

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| Field focus | Focus trong field | Viền inset 2px bằng `--chatty-contact-fg` | Không thêm ARIA |
| Invalid | Validation trả lỗi | Viền inset 1.5px bằng `--chatty-contact-error`; icon đổi sang màu lỗi; dòng lỗi dùng body-small | `aria-invalid`, `aria-describedby` trỏ tới dòng lỗi |
| Submit nghỉ / có giá trị | Chưa có giá trị / có giá trị hoặc focus-visible | opacity 0.55 khi chưa có giá trị; opacity 1 khi có giá trị hoặc focus-visible | Không thêm ARIA |
| Submit hover / active | Pointer | brightness(0.85) khi hover; scale(0.94) khi active | Không thêm ARIA |
| Submit focus-visible | Keyboard | Outline 2px bằng `--chatty-contact-fg` | Native focus |
| Pending | loading hoặc skip đang chạy | Field và nút disabled; opacity 0.5; spinner 18px quay 0.8s | `aria-busy`; nhãn nút `Loading` |
| Reduced motion | prefers-reduced-motion: reduce | Spinner không quay (animation none) | Không thêm ARIA |

### Behaviour

#### ContactComposer

| Interaction | Result |
| --- | --- |
| Enter trong input | Focus field kế tiếp; ở field cuối kiểm tra mọi field rồi gọi onSubmit. Khi IME đang compose thì không xử lý Enter. |
| Escape trong input | Gọi skip khi có onSkip và chặn lan truyền sự kiện. |
| Nút bỏ qua | Chạy onSkip với trạng thái skipping; nhãn đổi sang Loading và nút bị disable. |
| Validation | Bắt buộc theo required; email theo dạng a@b.c; phone chỉ gồm số và ký tự điện thoại, từ 7 đến 15 chữ số. |
| Kích hoạt lặp | Bỏ qua lần gọi khi loading hoặc khi đang chờ onSubmit hoặc onSkip. |
| Focus | Focus input khi có focusRequest hoặc focusOnMount, hoặc khi autoFocus và cửa sổ rộng hơn 899. |
| Chỉnh sửa | Gõ vào input xoá lỗi hiện tại và gọi onChange; giá trị do caller giữ. |

### Copy

#### ContactComposer

| String | i18n key | Where |
| --- | --- | --- |
| Email address | Email address | Placeholder và nhãn field email |
| Name | Name | Placeholder và nhãn field tên |
| Phone number | Phone number | Placeholder và nhãn field phone |
| Chat anonymously | Chat anonymously | Nút bỏ qua |
| Loading | Loading | Nhãn nút bỏ qua và nút gửi khi pending |
| Send message | Send message | aria-label nút gửi |
| Email is required | Email is required | Lỗi field email bắt buộc |
| Email is invalid | Email is invalid | Lỗi email sai dạng |
| Phone number is invalid | Phone number is invalid | Lỗi phone sai dạng hoặc ngoài khoảng chữ số |
| Caller-owned | Caller-owned | description và privacy do PreChatMsg truyền |

### Source

#### ContactComposer

| File | Evidence |
| --- | --- |
|  | API, cấu trúc, validation và ARIA |
|  | Kích thước, token fallback và state |
|  | Role chữ |

## AI Mode

### Import / element

#### ContactComposer

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| `ContactComposer` | @avada/chatty-ui/canonical/ContactComposer.jsx | .chatty-ai-mode[data-theme] |

### Anatomy

#### ContactComposer

| Part | Element |
| --- | --- |
| 1 | Mô tả tùy chọn trong `chatty-contact-description`; field email dùng nó làm aria-labelledby. |
| 2 | Nút bỏ qua trong `chatty-contact-skip`, chỉ render khi có `onSkip`. |
| 3 | Nhóm `chatty-contact-card` chứa các field: icon và input; field cuối có nút gửi. |
| 4 | Dòng lỗi trong `chatty-contact-error` với role alert. |
| 5 | Đồng ý bản tin khi có `newsletter`, rồi dòng privacy trong `chatty-contact-consent`. |

### Placement / order

#### ContactComposer

| Context | Order |
| --- | --- |
| Bên trong component | Mô tả, nút bỏ qua, nhóm field (icon, input; gửi ở field cuối), lỗi, đồng ý bản tin, privacy. |
| Caller AI Mode | ChatPreForm render ContactComposer; onSkip chỉ truyền khi mode là both. |

### Props

#### ContactComposer

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| `fields` | string[] | email, name, phone | email | Lọc theo thứ tự cố định; danh sách rỗng quay về email. |
| `required` | object | Cờ bắt buộc theo field | `{}` | Merchant đặt cờ cho từng field. |
| `description` | string | Do caller đặt | None | Render trong `chatty-contact-description`. |
| `privacy` | JSX.Element | Do caller đặt | None | Render trong `chatty-contact-consent` ở cuối. |
| `onSkip` | Function | Do caller đặt | None | Có giá trị mới hiện nút bỏ qua; Escape trong input cũng gọi. |
| `loading` | boolean | true / false | None | Cùng với skip đang chạy tạo trạng thái pending: disable field và nút, aria-busy. |
| `autoFocus` | boolean | true / false | `true` | autoFocus mặc định chỉ focus khi cửa sổ rộng hơn 899; focusRequest hoặc focusOnMount có thể focus trên mobile. |
| `inForm` | boolean | true / false | `false` | true: Root là div và nút gửi gọi submit qua onClick. |

### Sizes

#### ContactComposer

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Root | Theo nội dung | 8px 12px 12px | Không khai báo | Không khai báo | Kế thừa font của caller | Không áp dụng | Không có override theo viewport |
| Field | min-height 52px | 6px 9px 6px 14px | 10px | 28px | input-value Derived(15px = type(input-value, desktop, size)) / Derived(22px = type(input-value, desktop, line)) desktop → Derived(18px = type(input-value, mobile, size)) / Derived(24px = type(input-value, mobile, line)) mobile | Field cao tối thiểu 52px | JS .is-mobile ≤899px; hoặc media (hover: none) and (pointer: coarse) |
| Grouped fields | min-height 44px mỗi field | 0 6px 0 12px | 8px | Card 18px; field 17px | input-value | 44px mỗi input | Khi có nhiều field |
| Submit | 44px | 0 | Không khai báo | 50% | Icon 16px | 44px | Không có override theo viewport |
| Skip button | min-height 44px | 12px | 6px | 999px | button-label Derived(14px = type(button-label, desktop, size)) / Derived(18px = type(button-label, desktop, line)) desktop → Derived(17px = type(button-label, mobile, size)) / Derived(24px = type(button-label, mobile, line)) mobile | 44px | JS .is-mobile ≤899px; hoặc media (hover: none) and (pointer: coarse) |
| Error, consent | Theo nội dung | Error 6px 2px 0 | 6px | Không khai báo | body-small Derived(14px = type(body-small, desktop, size)) / Derived(20px = type(body-small, desktop, line)) desktop → Derived(15px = type(body-small, mobile, size)) / Derived(22px = type(body-small, mobile, line)) mobile | Không tương tác | JS .is-mobile ≤899px; hoặc media (hover: none) and (pointer: coarse) |

### Tokens

#### ContactComposer

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Chữ và viền field | `--chatty-contact-fg` | #1f1f1f | #ececec |
| Nền field | `--chatty-contact-bg` | rgba(255, 255, 255, 0.92) | rgba(40, 40, 40, 0.92) |
| Chữ phụ | `--chatty-contact-muted` | #6b6b6b | #a3a3a3 |
| Placeholder | `--chatty-contact-placeholder` | #6b6b6b | #8d8d8d |
| Viền nút bỏ qua | `--chatty-contact-line` | rgba(0, 0, 0, 0.1) | rgba(255, 255, 255, 0.12) |
| Nền nút bỏ qua | `--chatty-contact-chip` | rgba(255, 255, 255, 0.7) | rgba(40, 40, 40, 0.7) |
| Lỗi | `--chatty-contact-error` | #dc2626 | #f87171 |
| Màu nhấn đồng ý bản tin | `--chatty-contact-accent` | `var(--accent)` | `var(--accent)` |

### States

#### ContactComposer

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| Field focus | Focus trong field | Viền inset 2px bằng `--chatty-contact-fg` | Không thêm ARIA |
| Invalid | Validation trả lỗi | Viền inset 1.5px bằng `--chatty-contact-error`; icon đổi sang màu lỗi; dòng lỗi dùng body-small | `aria-invalid`, `aria-describedby` trỏ tới dòng lỗi |
| Submit nghỉ / có giá trị | Chưa có giá trị / có giá trị hoặc focus-visible | opacity 0.55 khi chưa có giá trị; opacity 1 khi có giá trị hoặc focus-visible | Không thêm ARIA |
| Submit hover / active | Pointer | brightness(0.85) khi hover; scale(0.94) khi active | Không thêm ARIA |
| Submit focus-visible | Keyboard | Outline 2px bằng `--chatty-contact-fg` | Native focus |
| Pending | loading hoặc skip đang chạy | Field và nút disabled; opacity 0.5; spinner 18px quay 0.8s | `aria-busy`; nhãn nút `Loading` |
| Reduced motion | prefers-reduced-motion: reduce | Spinner không quay (animation none) | Không thêm ARIA |

### Behaviour

#### ContactComposer

| Interaction | Result |
| --- | --- |
| Enter trong input | Focus field kế tiếp; ở field cuối kiểm tra mọi field rồi gọi onSubmit. Khi IME đang compose thì không xử lý Enter. |
| Escape trong input | Gọi skip khi có onSkip và chặn lan truyền sự kiện. |
| Nút bỏ qua | Chạy onSkip với trạng thái skipping; nhãn đổi sang Loading và nút bị disable. |
| Validation | Bắt buộc theo required; email theo dạng a@b.c; phone chỉ gồm số và ký tự điện thoại, từ 7 đến 15 chữ số. |
| Kích hoạt lặp | Bỏ qua lần gọi khi loading hoặc khi đang chờ onSubmit hoặc onSkip. |
| Focus | Focus input khi có focusRequest hoặc focusOnMount, hoặc khi autoFocus và cửa sổ rộng hơn 899. |
| Chỉnh sửa | Gõ vào input xoá lỗi hiện tại và gọi onChange; giá trị do caller giữ. |

### Copy

#### ContactComposer

| String | i18n key | Where |
| --- | --- | --- |
| Email address | Email address | Placeholder và nhãn field email |
| Name | Name | Placeholder và nhãn field tên |
| Phone number | Phone number | Placeholder và nhãn field phone |
| Chat anonymously | Chat anonymously | Nút bỏ qua |
| Loading | Loading | Nhãn nút bỏ qua và nút gửi khi pending |
| Send message | Send message | aria-label nút gửi |
| Email is required | Email is required | Lỗi field email bắt buộc |
| Email is invalid | Email is invalid | Lỗi email sai dạng |
| Phone number is invalid | Phone number is invalid | Lỗi phone sai dạng hoặc ngoài khoảng chữ số |
| Caller-owned | Caller-owned | description và privacy do ChatPreForm truyền |

### Source

#### ContactComposer

| File | Evidence |
| --- | --- |
|  | API, cấu trúc, validation và ARIA |
|  | Kích thước, token fallback và state |
|  | Role chữ |

## Do / Don't

Do: giữ giá trị đang nhập khi validation lỗi và hiện lỗi ngay dưới field.

Don't: gửi khi có field bắt buộc chưa hợp lệ hoặc gọi lại submit trong khi đang pending.

## Accessibility

| Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio |
| --- | --- | --- | --- | --- |
| Classic | Root là form, hoặc div khi inForm; input được đặt tên bằng aria-labelledby hoặc aria-label; nút gửi có aria-label. | Enter chuyển field hoặc gửi ở field cuối; Escape gọi skip khi có `onSkip`. Khi lỗi, focus field lỗi đầu tiên, aria-describedby trỏ tới lỗi và gõ tiếp xoá lỗi. Không có control Retry riêng: người dùng sửa giá trị rồi gửi lại. | Lỗi nằm trong role alert; nút gửi đặt aria-busy khi pending; không có live region cho trạng thái thành công. | Light Measured(#1f1f1f / #f2f2f2 = 14.72:1); Dark Measured(#ececec / #262626 = 12.81:1) |
| AI Mode | Root là form, hoặc div khi inForm; input được đặt tên bằng aria-labelledby hoặc aria-label; nút gửi có aria-label. | Enter chuyển field hoặc gửi ở field cuối; Escape gọi skip khi có `onSkip`. Khi lỗi, focus field lỗi đầu tiên, aria-describedby trỏ tới lỗi và gõ tiếp xoá lỗi. Không có control Retry riêng: người dùng sửa giá trị rồi gửi lại. | Lỗi nằm trong role alert; nút gửi đặt aria-busy khi pending; không có live region cho trạng thái thành công. | Không đo tỉ lệ vì nền field có alpha, cần nền đặc để tính |


-  .Avada-Faqs_Popup[data-theme='dark']
