# Message grouping + time

Nhóm tin cùng người gửi và đặt mốc ngày, giờ đúng chỗ theo code đang chạy của AI Mode và inbox.

## Key rules

- AI Mode: giữa các cụm là `var(--chatty-space-400)`, trong một cụm là `var(--chatty-space-050)`; ngày hiện bằng một day divider riêng.
- Admin: một cụm là các tin cùng người gửi, cùng ngày và cách nhau dưới `MESSAGE_CLUSTER_GAP_MS`; giữa cụm `$gap-cluster`, trong cụm 2px.
- Admin: `MessageFrame` ghép nhãn trạng thái vào metadata; `lastSelfId` đánh dấu receipt cuối, sending / failed được ưu tiên.
- Giờ chỉ hiện ở tin cuối cụm (và tin failed hoặc đang gửi); các tin khác hiện giờ đầy đủ trong tooltip khi hover / focus. Tên người gửi gộp theo run: cùng người, cùng ngày.

## Use when / Avoid

Dùng khi một người gửi liên tiếp nhiều tin ngắn. Classic dùng renderer riêng (LegacyMessageFrame) nên trang này không mô tả Classic.

### Use instead

| Component | Use when |
| --- | --- |
| `MessageFrame` | Inbox admin: nhóm tin, day divider và trạng thái giao tin. |
| `ChatMessage` | AI Mode: run head quyết định tên; cụm quyết định class grouped và giờ ở tin cuối cụm. |

## Entry points

| Surface | Owner |
| --- | --- |
| AI Mode | ChatMessage do ChatThread render theo getMessageGrouping |
| Admin | `CanonicalSurface` trong InboxV2ChatArea render MessageFrame |

## Flow

| Surface | Step | Trigger | UI shown | Component | Copy + i18n key | Timing |
| --- | --- | --- | --- | --- | --- | --- |
| AI Mode | Đầu cụm | Sender khác, ngày khác hoặc cách tin trước từ `MESSAGE_CLUSTER_GAP_MS` | Tên người gửi ở đầu run; giờ ở tin cuối cụm | ChatMessage | Giờ: formatMessageTime / Caller-owned | Tính khi render |
| AI Mode | Trong cụm | isClusterHead false | Class grouped; margin-top `var(--chatty-space-050)`; giờ đầy đủ trong tooltip | ChatMessage | Không có chữ riêng | Tính khi render |
| Admin | Đầu cụm | groupedWithPrev false | Sender row ở đầu run; giờ ở tin cuối cụm | MessageFrame | Giờ: formatMessageTime / Caller-owned | Tính khi render |
| Admin | Trong cụm | isSameClusterAs true | Class grouped-prev; margin-top 2px; giờ đầy đủ trong tooltip | MessageFrame | Không có chữ riêng | Tính khi render |

## Edge cases

| Surface | Case | Behaviour |
| --- | --- | --- |
| AI Mode | Tin đầu tiên của ngày | Day divider đứng trên tin; hàng sau divider có margin-top 0 |
| Admin | Hai tin cùng người gửi cách nhau từ `MESSAGE_CLUSTER_GAP_MS` | Tách cụm, mỗi cụm có giờ ở tin cuối; tên không lặp lại vì vẫn cùng run (`run-prev`) |
| Admin | Hàng centered hoặc compact | Không gộp nhóm và không có giờ |
| Admin | Tin note và tin reply liền nhau | Không gộp để không mất delivery status của reply |

## Live preview

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

### Standard

Example (Standard) — Thread Standard dùng fixture cục bộ.

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

function grouping(surface) {
  const store = fixtureStore([
    {...question, text: 'Can you help me track my order?'},
    {
      id: 'a1',
      senderType: 'agent',
      senderMeta: {name: 'Alex'},
      text: 'Yes, I can help.',
      createdAt: '2026-01-15T10:01:00Z'
    },
    {
      id: 'a2',
      senderType: 'agent',
      senderMeta: {name: 'Alex'},
      text: 'Your parcel is in transit.',
      createdAt: '2026-01-15T10:02:00Z'
    },
    {
      id: 'a3',
      senderType: 'agent',
      senderMeta: {name: 'Alex'},
      text: 'A new update after five minutes.',
      createdAt: '2026-01-15T10:07:00Z'
    },
    {
      id: 'next-day',
      senderType: 'agent',
      senderMeta: {name: 'Alex'},
      text: 'Delivered the following day.',
      createdAt: '2026-01-16T10:07:00Z'
    }
  ]);
  return patternShell({surface, store});
}
export function Standard({surface}) {
  return grouping(surface);
}
```

Example (Standard) — Admin sender grouping.

```js
import '@avada/chatty-ui/tokens/admin.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>`;
}

function grouping(surface) {
  const store = fixtureStore([
    {...question, text: 'Can you help me track my order?'},
    {
      id: 'a1',
      senderType: 'agent',
      senderMeta: {name: 'Alex'},
      text: 'Yes, I can help.',
      createdAt: '2026-01-15T10:01:00Z'
    },
    {
      id: 'a2',
      senderType: 'agent',
      senderMeta: {name: 'Alex'},
      text: 'Your parcel is in transit.',
      createdAt: '2026-01-15T10:02:00Z'
    },
    {
      id: 'a3',
      senderType: 'agent',
      senderMeta: {name: 'Alex'},
      text: 'A new update after five minutes.',
      createdAt: '2026-01-15T10:07:00Z'
    },
    {
      id: 'next-day',
      senderType: 'agent',
      senderMeta: {name: 'Alex'},
      text: 'Delivered the following day.',
      createdAt: '2026-01-16T10:07:00Z'
    }
  ]);
  return patternShell({surface, store});
}
export function StandardAdmin() {
  return grouping('admin');
}
```

Fixture có cùng sender, cách đúng 5 phút và qua ngày để thấy grouping, clock và divider. Admin dùng self-types agent/bot.

### Current

Example (Current (React), being replaced) — MessageFrame thật: trạng thái sent và sending trong metadata; dữ liệu cục bộ.

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

export function Status() {
  return (
    <div>
      <MessageFrame
        vm={{
          id: 'sent',
          senderType: 'agent',
          text: 'Reply sent',
          status: 'sent',
          createdAt: '2026-11-19T08:00:00Z'
        }}
        viewerType="agent"
        TextRenderer={({text}) => text}
        lastSelfId="sent"
        hideDayDividers
        renderStatus={() => 'Seen'}
      />
      <MessageFrame
        vm={{id: 'sending', senderType: 'agent', text: 'Next reply', status: 'sending'}}
        viewerType="agent"
        TextRenderer={({text}) => text}
        hideDayDividers
      />
    </div>
  );
}
```

## AI Mode

### Import / element

#### ChatMessage

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| `ChatMessage` | @scripttag/v2/views/chat/ChatMessage.jsx | .chatty-ai-mode .chatty-chat-viewport |

#### Day divider

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| Day divider (hàm cục bộ của ChatThread) |  | .chatty-ai-mode .chatty-chat-viewport |

### Anatomy

#### ChatMessage

| Part | Element |
| --- | --- |
| 1 | Head: avatar và tên người gửi, chỉ ở đầu run. |
| 2 | Body của tin. |
| 3 | Metadata giờ dưới tin cuối cụm hoặc tin đang gửi; tin khác có tooltip giờ đầy đủ. |

#### Day divider

| Part | Element |
| --- | --- |
| 1 | Hàng separator chứa nhãn ngày. |
| 2 | Nhãn pill. |

### Placement / order

#### ChatMessage

| Context | Order |
| --- | --- |
| Thread | Head trước body; hàng nối tiếp cùng run bỏ head. |

#### Day divider

| Context | Order |
| --- | --- |
| Thread | Đứng trên tin đầu tiên của một ngày dương lịch. |

### Props

#### ChatMessage

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| `isClusterHead` | boolean | true / false | Caller | Đầu cụm; false thêm class grouped. |
| `isRunHead` | boolean | true / false | `isClusterHead` | Đầu run hiện head (avatar, tên). |
| `isClusterTail` | boolean | true / false | true | Tin cuối cụm hiện metadata giờ; tin khác có tooltip giờ. |
| `isPendingTail` | boolean | true / false | `isClusterTail` | Tin đang gửi cuối cùng hiện trạng thái gửi. |

#### Day divider

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| `date` | Date hoặc string | Ngày của tin | Caller | Nhãn tính bằng formatDayDivider. |

### Sizes

#### ChatMessage

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Khoảng cách giữa cụm | — | — | `var(--chatty-space-400)` | — | — | — | Mọi con trực tiếp của viewport |
| Trong cụm | — | — | `var(--chatty-space-050)` | Góc trên `var(--radius-xs)` phía người gửi | — | — | Class grouped |

#### Day divider

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Hàng divider | — | `var(--chatty-space-300) 0` | — | — | — | — | Mobile padding-block 8px |
| Pill | — | `var(--chatty-space-100) var(--chatty-space-300)` | — | `var(--radius-pill)` | `heading-small` | — | Cùng anatomy với day float |

### Tokens

#### ChatMessage

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Metadata giờ | Not available | — | — |

#### Day divider

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Viền pill | `--glass-edge` | 1px solid | Theo theme AI Mode |
| Nền pill | `--bg-elevated` | Theo theme AI Mode | Theo theme AI Mode |
| Chữ pill | `--vib-2` | Theo theme AI Mode | Theo theme AI Mode |

### States

#### ChatMessage

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| Grouped | isClusterHead false | Thêm class chatty-chat-msg--grouped; head chỉ ẩn khi isRunHead false; giờ vào tooltip | Tooltip giờ `aria-hidden` |

#### Day divider

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| Mặc định | Có tin của ngày mới | box-shadow none; không có hairline | role separator, aria-label là nhãn ngày |

### Behaviour

#### ChatMessage

| Interaction | Result |
| --- | --- |
| Giờ | Trong phút đầu hiện justNow; sau đó hiện giờ theo locale. |

#### Day divider

| Interaction | Result |
| --- | --- |
| Nhãn | Today, Yesterday, tên thứ trong tuần, hoặc ngày viết đầy đủ. |
| Day float | Hook useStickyDayDivider nổi ngày đang đọc trên viewport. |

### Copy

#### ChatMessage

| String | i18n key | Where |
| --- | --- | --- |
| Metadata giờ | Caller-owned | Nhãn thời gian do labels của caller |

#### Day divider

| String | i18n key | Where |
| --- | --- | --- |
| Today / Yesterday | Caller-owned (labels) | useTimeLabels của widget |

### Source

#### ChatMessage

| File | Evidence |
| --- | --- |
|  | Run head, cụm và tooltip giờ |
|  | Khoảng cách viewport |

#### Day divider

| File | Evidence |
| --- | --- |
|  | DayDivider |
|  | Divider và pill |

## Admin

### Import / element

#### MessageFrame

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| `MessageFrame` | @avada/chatty-ui/canonical | .inbox-v2 |

### Anatomy

#### MessageFrame

| Part | Element |
| --- | --- |
| 1 | Day divider trước tin đầu ngày. |
| 2 | Sender row với tên; metadata giờ và receipt cạnh bubble. |
| 3 | Bubble và body. |

### Placement / order

#### MessageFrame

| Context | Order |
| --- | --- |
| Thread | Divider, gutter, sender row, bubble với metadata, footer. |

### Props

#### MessageFrame

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| `prev` / `next` | vm | Tin liền trước / sau | prev | Dùng để tính grouped-prev và grouped-next. |
| `renderStatus` | Function | Nhãn theo vm và isLastSelf | defaultStatusLabel | Metadata dùng nhãn của caller. |
| `hideDayDividers` | boolean | true / false | undefined | Tắt day divider. |
| `MESSAGE_CLUSTER_GAP_MS` | hằng số | `5 * 60 * 1000` | — | Cùng run và cách nhau dưới ngưỡng thì gộp cụm; từ ngưỡng trở lên tách cụm. |

### Sizes

#### MessageFrame

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Giữa các cụm | — | — | `map.get(layout.$spaces, 400) * 1px` | — | — | — | margin-top của hàng |
| Trong cụm | — | — | 2px | — | — | — | Class grouped-prev |
| Divider | — | `var(--chatty-space-300, 12px) 0` | — | — | — | — | Hàng đầu và hàng sau divider có margin-top 0 |

### Tokens

#### MessageFrame

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Pill ngày | `--chatty-color-text-secondary` | #616161 | No Dark skin |
| Viền pill | `--chatty-color-border` | #e3e3e3 | No Dark skin |

### States

#### MessageFrame

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| Grouped | Cùng run, dưới `MESSAGE_CLUSTER_GAP_MS` | Class chatty-message--grouped-prev; margin-top 2px | Không thêm ARIA |
| Metadata | Tin cuối cụm, tin failed hoặc tin đang gửi cuối | Hiện giờ và receipt; tin khác trong cụm có tooltip giờ đầy đủ khi hover / focus | Tooltip `aria-hidden` |

### Behaviour

#### MessageFrame

| Interaction | Result |
| --- | --- |
| Metadata giờ | Trong phút đầu hiện justNow; sau đó giờ theo locale, kèm ngày giờ đầy đủ trong nhãn truy cập. |
| Gộp nhóm | Run: cùng senderType, cùng ngày, cùng senderId nếu là agent. Cụm: thêm điều kiện cách nhau dưới `MESSAGE_CLUSTER_GAP_MS`. |

### Copy

#### MessageFrame

| String | i18n key | Where |
| --- | --- | --- |
| Nhãn giờ / ngày | labels của caller (`timeLabels`) | Truyền qua prop |

### Source

#### MessageFrame

| File | Evidence |
| --- | --- |
|  | Quy tắc run và cụm |
|  | Ngưỡng cụm |
|  | Margin giữa nhóm |
|  | Margin trong nhóm |

## Do / Don't

Do: gộp tên người gửi theo run và đặt giờ ở tin cuối cụm như renderer của surface; giữ giờ đầy đủ trong tooltip.

Don't: hiện giờ trên mọi tin trong cụm hoặc thêm hairline vào day divider.

## Accessibility

| Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio |
| --- | --- | --- | --- | --- |
| AI Mode | Day divider có role separator và aria-label là nhãn ngày | Không focusable | Không có live region riêng | Không khai báo cặp màu trong cell |
| Admin | Day divider có role separator; bubble có role group và aria-label gồm người gửi, giờ và nội dung | Không focusable | Không có live region riêng | Không khai báo cặp màu trong cell |


-  .chatty-chat-viewport:".chatty-ai-mode .chatty-chat-viewport { >"
