# Waiting + streaming

Dòng chờ một nhãn thật rồi hiện chữ trả lời theo nhịp, cùng primitive trên AI Mode và Classic.

## Key rules

- AI Mode: một dòng `ThinkingIndicator` cao 24px nằm ở vị trí câu trả lời cho tới khi `useSmoothText` có chữ đầu.
- Classic: cùng `ThinkingIndicator` qua WidgetThinkingBlock; chữ trả lời đi qua `useSmoothText` trong WidgetTextRenderer.
- Nhãn chờ đổi khi có tín hiệu thật hoặc qua mốc thời gian từ lúc gửi; không hứa thời gian hoàn tất.
- Reduced motion: dừng shimmer và chấm, chữ trả lời hiện ngay không fade từng từ.

## Use when / Avoid

Dùng khi khách vừa gửi và đang chờ chữ đầu tiên. Không dùng cho lỗi (xem Error + retry) hay cho trạng thái người thật đang gõ.

### Use instead

| Component | Use when |
| --- | --- |
| `ThinkingIndicator` | Nhãn chờ một dòng cho tới khi chữ trả lời xuất hiện. |
| `useSmoothText` | Lộ chữ đã stream theo nhịp chunk thay vì nhảy từng khối. |

## Entry points

| Surface | Owner |
| --- | --- |
| AI Mode | Caller ChatThread và AssistantText |
| Classic | Caller WidgetThinkingBlock và WidgetTextRenderer, đăng ký trong widgetRegistry |

## Flow

| Surface | Step | Trigger | UI shown | Component | Copy + i18n key | Timing |
| --- | --- | --- | --- | --- | --- | --- |
| AI Mode | Chờ | `view.prompt` là bot-typing | Dòng chờ trong statusline | ThinkingIndicator | Finding your answer… | Hiện ngay khi prompt đổi |
| AI Mode | Nhãn theo công cụ | `activityCode` là product_lookup | Đổi sang Finding products for you… | ThinkingIndicator | Finding products for you… | Theo tín hiệu thật |
| AI Mode | Nhắc chờ | Qua `WAITING_REASSURANCE_MS` | Nhãn thứ hai | ThinkingIndicator | Still on it — thanks for waiting… | 12000 (ms) sau khi gửi |
| AI Mode | Chờ lâu | Qua `WAITING_LONG_REPLY_MS` | Nhãn thứ ba | ThinkingIndicator | This one is taking a bit longer. Your answer will appear right here. | 30000 (ms) sau khi gửi |
| AI Mode | Chữ đầu | `useSmoothText` trả về chuỗi không rỗng | Markdown thay dòng chờ | useSmoothText | Nội dung trả lời | Theo `rate` của animator |
| Classic | Chờ | Block loading hoặc reasoning của AI | ThinkingIndicator, kèm tile grid khi có | ThinkingIndicator | Finding your answer… | Theo block của registry |
| Classic | Chữ đầu | Message đang stream | StreamingText render Markdown có `animate` | useSmoothText | Nội dung trả lời | Theo `rate` của animator |

## Edge cases

| Surface | Case | Behaviour |
| --- | --- | --- |
| AI Mode | Cụm chờ tuỳ chỉnh | Khi `isCustom`, nhãn quay vòng theo `THINKING_STATUS_ROTATE_MS` thay cho các mốc |
| AI Mode | Có tile grid | Không render waitingStatus khi `showTileGrid` |
| AI Mode | Reduced motion | Dot và label bỏ animation; chữ trả lời hiện ngay |
| Classic | Cụm chờ tuỳ chỉnh | Khi `isCustom`, nhãn quay vòng theo `THINKING_STATUS_ROTATE_MS` |
| Classic | Block loading của người gửi khác AI | Dùng LoadingBlock thay cho ThinkingIndicator |
| Classic | Reduced motion | Dot và label bỏ animation; chữ trả lời hiện ngay |

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

Example (Standard) — Standard: complete widget, fixture conversation and surface dimensions.

```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>`;
}

const strings = {
  header: 'Store assistant',
  message: 'Message',
  send: 'Send',
  waiting: 'Finding your answer…',
  products: 'Finding products for you…',
  reassurance: 'Still on it — thanks for waiting…',
  longReply: 'This one is taking a bit longer. Your answer will appear right here.',
  answer: 'The **canvas tote** is lightweight and reusable.',
  you: 'You'
};
export function Standard({surface}) {
  let answerId = 'answer';
  const waiting = text => ({
    id: answerId,
    senderType: 'bot',
    blocks: [{type: 'loading', text}],
    hasEventTime: false
  });
  const store = fixtureStore([question, waiting(strings.waiting)]);
  const subscribe = store.subscribe;
  let users = 0;
  let timers = [];
  store.cancel = () => {
    timers.forEach(clearTimeout);
    timers = [];
  };
  const start = (newQuestion = false) => {
    store.cancel();
    if (newQuestion) {
      store.setMessages(
        store
          .getState()
          .messages.map(m =>
            m.id === answerId ? {...m, blocks: undefined, text: strings.answer, status: 'sent'} : m
          )
      );
    }
    if (newQuestion) answerId = `answer-${store.getState().messages.length}`;
    const updateAnswer = answer => {
      const messages = store.getState().messages;
      store.setMessages(
        messages.some(m => m.id === answerId)
          ? messages.map(m => (m.id === answerId ? answer : m))
          : [...messages, answer]
      );
    };
    const finish = (text, status = 'streaming') =>
      updateAnswer({id: answerId, senderType: 'bot', text, status, hasEventTime: false});
    if (matchMedia('(prefers-reduced-motion: reduce)').matches) {
      finish(strings.answer, 'sent');
      return;
    }
    updateAnswer(waiting(strings.waiting));
    const after = (ms, fn) => timers.push(setTimeout(fn, ms));
    if (surface === 'ai-mode') {
      after(2000, () => updateAnswer(waiting(strings.products)));
      after(12000, () => updateAnswer(waiting(strings.reassurance)));
      after(30000, () => updateAnswer(waiting(strings.longReply)));
    }
    const first = surface === 'ai-mode' ? 32000 : 2000;
    after(first, () => finish('The **canvas tote**'));
    after(first + 600, () => finish(strings.answer, 'sent'));
  };
  store.subscribe = listener => {
    const release = subscribe(listener);
    if (users++ === 0) queueMicrotask(start);
    return () => {
      release();
      if (--users === 0) store.cancel();
    };
  };
  return patternShell({surface, store, strings, onSend: () => start(true)});
}
```

S5: nhóm Waiting / Tool / 12s / 30s / First text nằm ngoài widget; chọn để nhảy tức thì tới trạng thái fixture. Controls không được copy vào Code Standard. Composer vẫn giữ lịch sử; reduced-motion trả lời ngay.

Current: các story React bên dưới giữ nguyên.

Example (Current (React), being replaced) — ChatThread thật ở khoảnh khắc chờ: câu hỏi vừa gửi, dòng ThinkingIndicator ở vị trí câu trả lời; trạng thái đóng băng, không timer.

```jsx
import React, {useState} from 'react';
import ChatThread from '@scripttag/v2/views/ChatThread.jsx';
import {chatStore} from '@scripttag/v2/stores/chatStore.js';
import {WidgetThinkingBlock} from '@assets/pages/InboxManagement/v2/blocks/WidgetThinkingBlock.jsx';
import {WidgetTextRenderer} from '@assets/pages/InboxManagement/v2/blocks/WidgetTextRenderer.jsx';

const at = minutes => new Date(Date.parse('2026-01-15T10:00:00Z') + minutes * 60000);
const question = {
  id: 'm1',
  senderType: 'customer',
  text: 'Which jacket should I pick for hiking?',
  blocks: [],
  createdAt: at(0)
};
const reply = text => ({
  id: 'm2',
  senderType: 'bot',
  senderName: 'Assistant',
  text,
  blocks: [],
  createdAt: at(1)
});
const partial = 'The Trail Shell is waterproof and packs into its own pocket. For colder weather the Ridge';

// A frozen moment: the store holds one fixed turn state, so no timer or stream runs.
function seed(state) {
  chatStore.setState({
    loadedId: 'guide-conversation',
    conversation: {id: 'guide-conversation'},
    ...state
  });
  return true;
}

// The widget gives the thread a fixed-height viewport; without one the thread's reserved reply space grows with its own height.
function Viewport() {
  return (
    <div style={{height: 420, display: 'flex', flexDirection: 'column'}}>
      <ChatThread isActive navigate={false} />
    </div>
  );
}

export function Waiting() {
  const [ready] = useState(() =>
    seed({messages: [question], awaitingReply: true, statusText: 'Finding your answer…'})
  );
  return ready ? <Viewport /> : null;
}
```

Example (Current (React), being replaced) — ChatThread thật khi đã có chữ đầu của câu trả lời; một khoảnh khắc cố định của luồng chữ.

```jsx
import React, {useState} from 'react';
import ChatThread from '@scripttag/v2/views/ChatThread.jsx';
import {chatStore} from '@scripttag/v2/stores/chatStore.js';
import {WidgetThinkingBlock} from '@assets/pages/InboxManagement/v2/blocks/WidgetThinkingBlock.jsx';
import {WidgetTextRenderer} from '@assets/pages/InboxManagement/v2/blocks/WidgetTextRenderer.jsx';

const at = minutes => new Date(Date.parse('2026-01-15T10:00:00Z') + minutes * 60000);
const question = {
  id: 'm1',
  senderType: 'customer',
  text: 'Which jacket should I pick for hiking?',
  blocks: [],
  createdAt: at(0)
};
const reply = text => ({
  id: 'm2',
  senderType: 'bot',
  senderName: 'Assistant',
  text,
  blocks: [],
  createdAt: at(1)
});
const partial = 'The Trail Shell is waterproof and packs into its own pocket. For colder weather the Ridge';

// A frozen moment: the store holds one fixed turn state, so no timer or stream runs.
function seed(state) {
  chatStore.setState({
    loadedId: 'guide-conversation',
    conversation: {id: 'guide-conversation'},
    ...state
  });
  return true;
}

// The widget gives the thread a fixed-height viewport; without one the thread's reserved reply space grows with its own height.
function Viewport() {
  return (
    <div style={{height: 420, display: 'flex', flexDirection: 'column'}}>
      <ChatThread isActive navigate={false} />
    </div>
  );
}

export function Streaming() {
  const [ready] = useState(() => seed({messages: [question, reply(partial)]}));
  return ready ? <Viewport /> : null;
}

const block = {type: 'reasoning', senderType: 'ai', text: 'Finding your answer…', turnKey: 'guide-turn'};
```

Example (Current (React), being replaced) — WidgetThinkingBlock thật: ThinkingIndicator của Classic.

```jsx
import React, {useState} from 'react';
import ChatThread from '@scripttag/v2/views/ChatThread.jsx';
import {chatStore} from '@scripttag/v2/stores/chatStore.js';
import {WidgetThinkingBlock} from '@assets/pages/InboxManagement/v2/blocks/WidgetThinkingBlock.jsx';
import {WidgetTextRenderer} from '@assets/pages/InboxManagement/v2/blocks/WidgetTextRenderer.jsx';

const at = minutes => new Date(Date.parse('2026-01-15T10:00:00Z') + minutes * 60000);
const question = {
  id: 'm1',
  senderType: 'customer',
  text: 'Which jacket should I pick for hiking?',
  blocks: [],
  createdAt: at(0)
};
const reply = text => ({
  id: 'm2',
  senderType: 'bot',
  senderName: 'Assistant',
  text,
  blocks: [],
  createdAt: at(1)
});
const partial = 'The Trail Shell is waterproof and packs into its own pocket. For colder weather the Ridge';

// A frozen moment: the store holds one fixed turn state, so no timer or stream runs.
function seed(state) {
  chatStore.setState({
    loadedId: 'guide-conversation',
    conversation: {id: 'guide-conversation'},
    ...state
  });
  return true;
}

// The widget gives the thread a fixed-height viewport; without one the thread's reserved reply space grows with its own height.
function Viewport() {
  return (
    <div style={{height: 420, display: 'flex', flexDirection: 'column'}}>
      <ChatThread isActive navigate={false} />
    </div>
  );
}

export function ClassicWaiting() {
  return <WidgetThinkingBlock block={block} vm={{id: 'm2', senderType: 'bot'}} />;
}
```

Example (Current (React), being replaced) — WidgetTextRenderer thật với chữ trả lời đã có.

```jsx
import React, {useState} from 'react';
import ChatThread from '@scripttag/v2/views/ChatThread.jsx';
import {chatStore} from '@scripttag/v2/stores/chatStore.js';
import {WidgetThinkingBlock} from '@assets/pages/InboxManagement/v2/blocks/WidgetThinkingBlock.jsx';
import {WidgetTextRenderer} from '@assets/pages/InboxManagement/v2/blocks/WidgetTextRenderer.jsx';

const at = minutes => new Date(Date.parse('2026-01-15T10:00:00Z') + minutes * 60000);
const question = {
  id: 'm1',
  senderType: 'customer',
  text: 'Which jacket should I pick for hiking?',
  blocks: [],
  createdAt: at(0)
};
const reply = text => ({
  id: 'm2',
  senderType: 'bot',
  senderName: 'Assistant',
  text,
  blocks: [],
  createdAt: at(1)
});
const partial = 'The Trail Shell is waterproof and packs into its own pocket. For colder weather the Ridge';

// A frozen moment: the store holds one fixed turn state, so no timer or stream runs.
function seed(state) {
  chatStore.setState({
    loadedId: 'guide-conversation',
    conversation: {id: 'guide-conversation'},
    ...state
  });
  return true;
}

// The widget gives the thread a fixed-height viewport; without one the thread's reserved reply space grows with its own height.
function Viewport() {
  return (
    <div style={{height: 420, display: 'flex', flexDirection: 'column'}}>
      <ChatThread isActive navigate={false} />
    </div>
  );
}

export function ClassicReply() {
  return <WidgetTextRenderer text={partial} format="markdown" vm={{id: 'm2', senderType: 'bot'}} />;
}
```

## AI Mode

### Import / element

#### ThinkingIndicator

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| `ThinkingIndicator` | @avada/chatty-ui/primitives/ThinkingIndicator.jsx | .chatty-ai-mode |

#### useSmoothText

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| `useSmoothText` | @avada/chatty-ui/primitives | Không có scope CSS |

### Anatomy

#### ThinkingIndicator

| Part | Element |
| --- | --- |
| 1 | `spanchatty-thinking` có `role="status"` và `aria-live`. |
| 2 | `chatty-thinking__previous`: nhãn cũ, `aria-hidden`, ẩn khi nhãn không đổi. |
| 3 | `chatty-thinking__label`: nhãn hiện tại có shimmer. |
| 4 | `chatty-thinking__dot`: chấm thay nhãn khi `text` rỗng. |

#### useSmoothText

| Part | Element |
| --- | --- |
| 1 | Hook trả về chuỗi `displayed` đã lộ ra. |
| 2 | `TextStreamAnimator` giữ `targetText`, `shown` và `rate`. |

### Placement / order

#### ThinkingIndicator

| Context | Order |
| --- | --- |
| AI Mode | Trong `chatty-chat-statusline` khi bot đang gõ, hoặc làm waitingStatus của tin bot cuối khi chờ hoặc đang stream, trừ khi hiện tile grid. |

#### useSmoothText

| Context | Order |
| --- | --- |
| AssistantText | Khi `smooth` rỗng trả về waitingStatus; khi có chữ render Markdown thay chỗ. |

### Props

#### ThinkingIndicator

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| `active` | boolean | true hoặc false | true | false thì component trả về null. |
| `text` | string | Nhãn chờ đã dịch | Chuỗi rỗng | Rỗng thì hiện chấm thay nhãn. |
| `sendKey` | string | Khoá lượt gửi | Chuỗi rỗng | Có giá trị thì chữ vào bằng fade theo đồng hồ gửi của viewport. |

#### useSmoothText

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| `text` | string | Toàn bộ chữ đã nhận | Bắt buộc | Dài hơn target thì push; không bắt đầu bằng target thì replay từ rỗng. |
| `streaming` | boolean | true hoặc false | Bắt buộc | false hoặc reduced motion thì snap ngay toàn bộ chữ. |

### Sizes

#### ThinkingIndicator

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Dòng chờ | 24px (`min-height` 24px) | Không có | Không có | Không có | Kế thừa cỡ chữ; line-height `--chatty-type-body-large-line` | Không tương tác | Một dòng nowrap; nhãn cắt bằng ellipsis |
| Chấm | 12px × 12px | Không có | Không có | 50% | Không có chữ | Không tương tác | Hiện khi nhãn rỗng |

#### useSmoothText

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Không có | Không có | Không có | Không có | Không có | Không có | Không có | Hook không render giao diện |

### Tokens

#### ThinkingIndicator

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Màu chữ nhãn | `--chatty-color-text` | `--vib-1`: rgba(20, 19, 24, 0.94) | rgba(255, 255, 255, 0.96) |
| Dòng chờ | `--chatty-thinking-ink` | Đặt bởi caller; nếu không có thì dùng `--chatty-color-text` | Cùng cơ chế |

#### useSmoothText

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Nhịp mặc định | `DEFAULT_GAP_MS` | 200 (ms) | Cùng giá trị |
| Sàn nhịp | `MIN_GAP_MS` | 60 (ms) | Cùng giá trị |
| Trần nhịp | `MAX_GAP_MS` | 700 (ms) | Cùng giá trị |
| Trọng số nhịp mới | `GAP_SMOOTHING` | 0.3 | Cùng giá trị |
| Độ chậm hơn nhịp đến | `PACE_SLACK` | 1.25 | Cùng giá trị |
| Fade mỗi từ (Markdown) | `FADE_MS` | 700 (ms), easing ease-out | Cùng giá trị |

### States

#### ThinkingIndicator

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| Shimmer | Nhãn có giá trị | Gradient 35% / 50% / 65%; chạy 1500ms linear infinite | Không thêm ARIA |
| Pulse | Nhãn rỗng | Chấm scale(0.75), 550ms linear infinite alternate | Không thêm ARIA |
| Đổi nhãn | `text` khác lần trước | Nhãn cũ mờ dần, nhãn mới hiện dần, `duration: 150` | Nhãn cũ `aria-hidden` |
| Vào theo lượt gửi | `sendKey` có giá trị | Bắt đầu trong suốt, fade hiện dần với `duration: 150` trừ phần đã trôi | Không thêm ARIA |
| Reduced motion | prefers-reduced-motion: reduce | Dot và label `animation: none`; nhãn dùng màu `--thinking-ink` | Không thêm ARIA |
| Forced colors | forced-colors: active | Nhãn dùng CanvasText, bỏ gradient và animation | Không thêm ARIA |

#### useSmoothText

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| Đang lộ chữ | `streaming` true, không reduced motion | `displayed` tăng theo `rate`, dừng ở ranh giới từ | Không thêm ARIA |
| Reduced motion | prefers-reduced-motion: reduce | Bỏ nhịp từng bước, hiện ngay toàn bộ chữ; Markdown bỏ fade từng từ | Không thêm ARIA |
| Tin mới | `text` không bắt đầu bằng target | Replay từ chuỗi rỗng | Không thêm ARIA |

### Behaviour

Đổi nhãn tại chỗ rồi bàn giao cho chữ đầu; không gán arrival event một delay cố định.

- Sequence: Observed status labels crossfade 150ms linear, delay 0ms, cùng hàng 24px (ThinkingIndicator.scss:6,25). Khi có ký tự đầu, consumer bỏ chỉ báo; track đổi nhãn không chứng minh crossfade indicator→answer. Không hiện hai status trùng nghĩa hay tự cuộn theo token. Các hàng property được trình bày tĩnh; chuyển động thật xem Live preview phía trên.
- Standard: Chuẩn handover/status: fade 150ms ease-out cubic-bezier(.19,.91,.38,1). Với N ký tự đã nhận, target reveal ≥400 chars/s và không quá 2.5s cho phần text đó: duration = min(N / 400, 2.5) seconds. Đây không phải thời gian chờ network. Word fade 700ms out. Nhãn source vẫn linear; reveal thực tế phụ thuộc arrival rate nên có thể chậm hơn target.
- Observed reveal: useSmoothText.js:4–11,31–40: N = text.length (UTF-16 code units), backlog = N − shown. Average gap khởi tạo 200ms; mỗi chunk mới cập nhật clamp(oldGap + .3 × (newGap − oldGap), 60, 700) ms. Rate = min(backlog / (avgGap_ms × 1.25), max(.4, N / 2500)) chars/ms; frame tiến tới whole-word boundary. Code hiện tại có thể chậm hơn target khi chunk đến chậm.
- Word fade: Markdown word spans fade opacity 0→1, 700ms native ease-out, khi mỗi word mount; không phải 700ms chờ sau first token.
- Reduced motion: Shimmer/dot dừng; nhãn vẫn fade 150ms linear; useSmoothText snap full text, Markdown bỏ word fade. Không dịch chuyển.
- Waiting loop: Observed shimmer 1500ms linear; dot 550ms alternate = chu kỳ 1100ms, trong dải chuẩn loop 1000–1600ms. Source ThinkingIndicator.scss:19,54,67.

No complete replay: Full handover and streaming need real first-character, chunk-arrival and word-mount events beyond these static property rows.

| Element | Property | From | To | Duration | Delay | Easing |
| --- | --- | --- | --- | --- | --- | --- |
| Old status | opacity | 1 | 0 | 150 ms | 0 ms | linear |
| New status | opacity | 0 | 1 | 150 ms | 0 ms | linear |
| New word | opacity | 0 | 1 | 700 ms | after word span mounts + 0 ms | ease-out |

Observed:;; ;  · AI Mode / admin · 2026-11-12

#### ThinkingIndicator

| Interaction | Result |
| --- | --- |
| Đổi nhãn | Nhãn cũ fade ra trong khi nhãn mới fade vào; hiệu ứng đổi nhãn không có nhánh reduced motion trong JS. |
| Ngừng | `active` false thì không render; caller quyết định khi nào dừng. |
| Phím và focus | Không có tab stop hay handler; dòng chờ không tương tác. |

#### useSmoothText

| Interaction | Result |
| --- | --- |
| Chunk mới | `push` tính lại nhịp trung bình và `rate` cho phần chưa lộ. |
| Ranh giới từ | Chỉ lộ tới ranh giới từ gần nhất; chữ CJK và Thái lộ theo ký tự. |
| Tốc độ | `rate` là min của tốc độ chunk đến và max(0.4, độ dài / 2500). |

### Copy

#### ThinkingIndicator

| String | i18n key | Where |
| --- | --- | --- |
| Finding your answer… | Finding your answer… | Nhãn mặc định đầu tiên, qua `i18nChat` |
| Still on it — thanks for waiting… | Still on it — thanks for waiting… | Mốc `WAITING_REASSURANCE_MS` |
| This one is taking a bit longer. Your answer will appear right here. | This one is taking a bit longer. Your answer will appear right here. | Mốc `WAITING_LONG_REPLY_MS` |
| Finding products for you… | Finding products for you… | Khi activityCode là product_lookup hoặc product_faq_lookup |
| Writing your answer… | Writing your answer… | Khi tín hiệu là Preparing results hoặc Almost ready |

#### useSmoothText

| String | i18n key | Where |
| --- | --- | --- |
| Không có | Không có | Hook không chứa chuỗi giao diện |

### Source

#### ThinkingIndicator

| File | Evidence |
| --- | --- |
|  | API, đổi nhãn, vào theo lượt gửi |
|  | Kích thước và chuyển động |
|  | Nhãn và mốc chờ |

#### useSmoothText

| File | Evidence |
| --- | --- |
|  | Animator và hook |
|  | Fade từng từ |

## Classic

### Import / element

#### ThinkingIndicator

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| `ThinkingIndicator` | @avada/chatty-ui/primitives/ThinkingIndicator.jsx | .Avada-Faqs_Popup |

#### useSmoothText

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| `useSmoothText` | @avada/chatty-ui/primitives | Không có scope CSS |

### Anatomy

#### ThinkingIndicator

| Part | Element |
| --- | --- |
| 1 | `spanchatty-thinking` có `role="status"` và `aria-live`. |
| 2 | `chatty-thinking__previous`: nhãn cũ, `aria-hidden`, ẩn khi nhãn không đổi. |
| 3 | `chatty-thinking__label`: nhãn hiện tại có shimmer. |
| 4 | `chatty-thinking__dot`: chấm thay nhãn khi `text` rỗng. |

#### useSmoothText

| Part | Element |
| --- | --- |
| 1 | Hook trả về chuỗi `displayed` đã lộ ra. |
| 2 | `TextStreamAnimator` giữ `targetText`, `shown` và `rate`. |

### Placement / order

#### ThinkingIndicator

| Context | Order |
| --- | --- |
| WidgetThinkingBlock | Sau tile grid (nếu `showTileGrid`) là ThinkingIndicator; block loading của người gửi khác AI dùng LoadingBlock. |

#### useSmoothText

| Context | Order |
| --- | --- |
| WidgetTextRenderer | Khi message đang stream render StreamingText gọi `useSmoothText` rồi Markdown. |

### Props

#### ThinkingIndicator

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| `active` | boolean | true hoặc false | true | false thì component trả về null. |
| `text` | string | Nhãn chờ đã dịch | Chuỗi rỗng | Rỗng thì hiện chấm thay nhãn. |
| `sendKey` | string | Khoá lượt gửi | Chuỗi rỗng | Có giá trị thì chữ vào bằng fade theo đồng hồ gửi của viewport. |

#### useSmoothText

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| `text` | string | Toàn bộ chữ đã nhận | Bắt buộc | Dài hơn target thì push; không bắt đầu bằng target thì replay từ rỗng. |
| `streaming` | boolean | true hoặc false | Bắt buộc | false hoặc reduced motion thì snap ngay toàn bộ chữ. |

### Sizes

#### ThinkingIndicator

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Dòng chờ | 24px (`min-height` 24px) | Không có | Không có | Không có | Kế thừa cỡ chữ; line-height `--chatty-type-body-large-line` | Không tương tác | Một dòng nowrap; nhãn cắt bằng ellipsis |
| Chấm | 12px × 12px | Không có | Không có | 50% | Không có chữ | Không tương tác | Hiện khi nhãn rỗng |

#### useSmoothText

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Không có | Không có | Không có | Không có | Không có | Không có | Không có | Hook không render giao diện |

### Tokens

#### ThinkingIndicator

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Màu chữ nhãn | `--chatty-color-text` | #303030 | #eee |
| Dòng chờ | `--chatty-thinking-ink` | Đặt bởi caller; nếu không có thì dùng `--chatty-color-text` | Cùng cơ chế |

#### useSmoothText

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Nhịp mặc định | `DEFAULT_GAP_MS` | 200 (ms) | Cùng giá trị |
| Sàn nhịp | `MIN_GAP_MS` | 60 (ms) | Cùng giá trị |
| Trần nhịp | `MAX_GAP_MS` | 700 (ms) | Cùng giá trị |
| Trọng số nhịp mới | `GAP_SMOOTHING` | 0.3 | Cùng giá trị |
| Độ chậm hơn nhịp đến | `PACE_SLACK` | 1.25 | Cùng giá trị |
| Fade mỗi từ (Markdown) | `FADE_MS` | 700 (ms), easing ease-out | Cùng giá trị |

### States

#### ThinkingIndicator

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| Shimmer | Nhãn có giá trị | Gradient 35% / 50% / 65%; chạy 1500ms linear infinite | Không thêm ARIA |
| Pulse | Nhãn rỗng | Chấm scale(0.75), 550ms linear infinite alternate | Không thêm ARIA |
| Đổi nhãn | `text` khác lần trước | Nhãn cũ mờ dần, nhãn mới hiện dần, `duration: 150` | Nhãn cũ `aria-hidden` |
| Vào theo lượt gửi | `sendKey` có giá trị | Bắt đầu trong suốt, fade hiện dần với `duration: 150` trừ phần đã trôi | Không thêm ARIA |
| Reduced motion | prefers-reduced-motion: reduce | Dot và label `animation: none`; nhãn dùng màu `--thinking-ink` | Không thêm ARIA |
| Forced colors | forced-colors: active | Nhãn dùng CanvasText, bỏ gradient và animation | Không thêm ARIA |

#### useSmoothText

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| Đang lộ chữ | `streaming` true, không reduced motion | `displayed` tăng theo `rate`, dừng ở ranh giới từ | Không thêm ARIA |
| Reduced motion | prefers-reduced-motion: reduce | Bỏ nhịp từng bước, hiện ngay toàn bộ chữ; Markdown bỏ fade từng từ | Không thêm ARIA |
| Tin mới | `text` không bắt đầu bằng target | Replay từ chuỗi rỗng | Không thêm ARIA |

### Behaviour

#### ThinkingIndicator

| Interaction | Result |
| --- | --- |
| Đổi nhãn | Nhãn cũ fade ra trong khi nhãn mới fade vào; hiệu ứng đổi nhãn không có nhánh reduced motion trong JS. |
| Ngừng | `active` false thì không render; caller quyết định khi nào dừng. |
| Phím và focus | Không có tab stop hay handler; dòng chờ không tương tác. |

#### useSmoothText

| Interaction | Result |
| --- | --- |
| Chunk mới | `push` tính lại nhịp trung bình và `rate` cho phần chưa lộ. |
| Ranh giới từ | Chỉ lộ tới ranh giới từ gần nhất; chữ CJK và Thái lộ theo ký tự. |
| Tốc độ | `rate` là min của tốc độ chunk đến và max(0.4, độ dài / 2500). |

### Copy

#### ThinkingIndicator

| String | i18n key | Where |
| --- | --- | --- |
| Finding your answer… | Finding your answer… | Nhãn mặc định đầu tiên, qua `i18nChat` |
| Still on it — thanks for waiting… | Still on it — thanks for waiting… | Mốc `WAITING_REASSURANCE_MS` |
| This one is taking a bit longer. Your answer will appear right here. | This one is taking a bit longer. Your answer will appear right here. | Mốc `WAITING_LONG_REPLY_MS` |
| Finding products for you… | Finding products for you… | Khi activityCode là product_lookup hoặc product_faq_lookup |
| Writing your answer… | Writing your answer… | Khi tín hiệu là Preparing results hoặc Almost ready |

#### useSmoothText

| String | i18n key | Where |
| --- | --- | --- |
| Không có | Không có | Hook không chứa chuỗi giao diện |

### Source

#### ThinkingIndicator

| File | Evidence |
| --- | --- |
|  | API, đổi nhãn, vào theo lượt gửi |
|  | Kích thước và chuyển động |
|  | Nhãn và mốc chờ |

#### useSmoothText

| File | Evidence |
| --- | --- |
|  | Animator và hook |
|  | Fade từng từ |

## Do / Don't

Do: nêu đúng bước đang chạy khi có tín hiệu thật.
Don't: hứa thời gian hoàn tất hoặc lặp một câu trấn an cố định vô hạn.

## Accessibility

| Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio |
| --- | --- | --- | --- | --- |
| AI Mode | `role="status"` trên dòng chờ, nằm trong statusline `aria-live` | Dòng chờ không có tab stop; không nhận focus | `role="status"` polite, cập nhật khi nhãn đổi | Không đo: màu nền do thread quyết định |
| Classic | `role="status"` trên dòng chờ | Dòng chờ không có tab stop; không nhận focus | `role="status"` polite, cập nhật khi nhãn đổi | Không đo: màu nền do thread quyết định |

