# Chatty UI Dùng cùng một hệ thống quy tắc để thiết kế AI Mode, Classic và admin inbox. ## Key rules - Giữ 1 primary action trong mỗi view. - Chuyển storefront sang mobile ở chiều rộng ≤899px. - Dành hit target ≥44px cho control trên mobile. - Giữ secondary text đạt contrast ≥4.5:1 trên nền sáng nhất. ## Overview Example — Ba tầng tài liệu và ba bề mặt Chatty; chọn một tầng để mở trang bắt đầu. ```jsx import React from 'react'; export function Overview() { return (
AI Mode với thread rộng và composer tách bên dưới
AI ModeThread và composer trên storefront. Nguồn: QA storefront, cắt từ ảnh desktop.
Classic với panel chat, thẻ sản phẩm và composer
ClassicPanel chat gọn. Nguồn: preview Product recommendation của guide.
Admin Inbox gồm danh sách hội thoại, thread và Details
Admin InboxWorkspace xử lý hội thoại. Nguồn: bản chụp Inbox có chú thích vùng.
Đi từ quy tắc đến control rồi tới luồng. Ba bề mặt dùng chung ngôn ngữ thiết kế, giữ bố cục riêng.
); } ``` ## Start here | Area | Use | | --- | --- | | [Brand](https://chatty-ui-research.avada-tesla-chatty.workers.dev/brand/) | Logo, màu và luật cho ấn phẩm Chatty. | | [Foundations](https://chatty-ui-research.avada-tesla-chatty.workers.dev/foundations/typography/) | Chọn type role, kích thước và hệ thống token. | | [Components](https://chatty-ui-research.avada-tesla-chatty.workers.dev/components/button/) | Chọn variant, state và cách đặt label. | | [Patterns](https://chatty-ui-research.avada-tesla-chatty.workers.dev/patterns/waiting-streaming/) | Ghép component thành luồng chờ và trả lời. | ## For agents Đọc [llms.txt](https://chatty-ui-research.avada-tesla-chatty.workers.dev/llms.txt) để chọn tài liệu hoặc [llms-full.txt](https://chatty-ui-research.avada-tesla-chatty.workers.dev/llms-full.txt) để lấy toàn bộ quy tắc. Dùng Copy Markdown trên mỗi trang để lấy nội dung sạch. ## Surface | Surface | Scope | | --- | --- | | AI Mode | Trải nghiệm mua sắm trên storefront. | | Classic | Chat widget truyền thống trên storefront. | | admin inbox | Hội thoại và công cụ của merchant. | - Chatty UI team decision - [Target size](https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum.html) - [Contrast](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html) --- # Brand Nhận diện thương hiệu Chatty cho ấn phẩm marketing: logo, màu, chữ, icon, hình. Không phải token sản phẩm. UI sản phẩm dùng [Foundations](https://chatty-ui-research.avada-tesla-chatty.workers.dev/foundations/colour-elevation/). Nguồn: Figma Chatty-branding-2025, bản agent 2026-11-16. Owner: Thu Le (PMM). [Download brand kit (.zip)](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-chatty-brand-kit.zip?v=1795057388) ## Logo | Light | Navy | Dark gradient | Light gradient | | --- | --- | --- | --- | | ![Logo Chatty trên trắng](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-logo-blue-white-bg.png?v=1795057545) | ![Logo Chatty trên navy](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-logo-white-blue-bg.png?v=1795057565) | ![Logo Chatty trên gradient tối](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-logo-white-dark-gradient-bg.png?v=1795057570) | ![Logo Chatty trên gradient sáng](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-logo-blue-light-gradient-bg.png?v=1795057541) | | Light icon | Navy icon | Dark gradient icon | Light gradient icon | | --- | --- | --- | --- | | ![Icon Chatty 0](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-icon-blue-white-bg.png?v=1795057520) | ![Icon Chatty 1](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-icon-white-blue-bg.png?v=1795057528) | ![Icon Chatty 2](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-icon-white-gradient-bg.png?v=1795057532) | ![Icon Chatty 3](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-icon-dark-gradient-bg.png?v=1795057524) | - Logo là bong bóng chat có 2 "mắt". Có 2 dạng: **icon** (chỉ bong bóng, dùng cho app icon, favicon, chỗ nhỏ) và **full logo** (bong bóng + chữ "chatty"). - Logo luôn nằm trên cùng, không bị pattern hay ảnh che. - Không đổi màu logo ngoài các bản có sẵn. Không kéo méo, không thêm bóng, không thêm viền. - Nền ảnh blog mặc định đã có sẵn logo, không chèn thêm logo thứ hai. | Background | File | Download | | --- | --- | --- | | Trắng | `logo/logo-blue-white-bg.png`, `logo/icon-blue-white-bg.png` | [logo-blue-white-bg.png](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-logo-blue-white-bg.png?v=1795057545), [icon-blue-white-bg.png](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-icon-blue-white-bg.png?v=1795057520) | | Trắng, cần bản đen | `logo/logo-black-white-bg.png` | [logo-black-white-bg.png](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-logo-black-white-bg.png?v=1795057536) | | Navy đặc | `logo/logo-white-blue-bg.png`, `logo/icon-white-blue-bg.png` | [logo-white-blue-bg.png](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-logo-white-blue-bg.png?v=1795057565), [icon-white-blue-bg.png](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-icon-white-blue-bg.png?v=1795057528) | | Gradient tối | `logo/logo-white-dark-gradient-bg.png`, `logo/icon-white-gradient-bg.png` | [logo-white-dark-gradient-bg.png](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-logo-white-dark-gradient-bg.png?v=1795057570), [icon-white-gradient-bg.png](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-icon-white-gradient-bg.png?v=1795057532) | | Gradient sáng | `logo/logo-blue-light-gradient-bg.png`, `logo/icon-dark-gradient-bg.png` | [logo-blue-light-gradient-bg.png](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-logo-blue-light-gradient-bg.png?v=1795057541), [icon-dark-gradient-bg.png](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-icon-dark-gradient-bg.png?v=1795057524) | | Trong suốt, đặt lên nền tuỳ ý | `logo/logo-navy-transparent.png`, `logo/logo-navy-transparent-hires.png`, `logo/logo-white-transparent.png` | [logo-navy-transparent.png](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-logo-navy-transparent.png?v=1795057557), [logo-navy-transparent-hires.png](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-logo-navy-transparent-hires.png?v=1795057552), [logo-white-transparent.png](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-logo-white-transparent.png?v=1795057573) | | Web | `logo/logo-website.webp` | [logo-website.webp](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-logo-website.webp?v=1795057561) | Do: Logo nằm trên cùng, trên nền đặc. Don't: Đổi màu, kéo méo, thêm bóng, thêm viền hoặc để pattern che logo. Vùng trống và kích thước tối thiểu chưa được chép. Xem Not yet defined. Nguồn: [brand-kit: brand-guidelines.agent.md §5](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-brand-guidelines.agent.md?v=1795057578). ## Colour ### Palette | Token | HEX | Role | | --- | --- | --- | | Navy (Primary/Blue/500) | `#06038D` | Màu chính. Chữ tiêu đề, nền tối, logo, CTA chính | | Light navy (Primary/Blue/50) | `#E6E6F4` | Nền nhạt, card, hover | | Yellow (Primary/Yellow/500) | `#FBC80B` | Điểm nhấn, highlight, số payoff, khung khoanh | | Purple (Secondary/Purple/500) | `#5750FE` | Màu phụ. Điểm nhấn chữ, link, primary UI (light mode) | | Black | `#000000` | Icon preset đen | | Gray | `#A2A2A2` | Màu accent của icon, vạch chia | | White | `#FFFFFF` | Nền sạch, chữ trên nền tối | | Neutral light | `#ECEDF1` | Nền phụ, card | **Màu ngoài token được phép:** | Context | Colour | Scope | | --- | --- | --- | | Only in aurora | `#4F49E7` | Đốm tím của nền aurora, chỉ dùng trong aurora. | | Product UI dark mode | `#7570F8` | Primary tím cho dark mode trong UI sản phẩm. Light mode vẫn `#5750FE`. | **Cách phối:** - Chữ trên nền sáng dùng navy, không dùng xám trung tính (kiểu `#52526B`). - Chữ vàng chìm trên nền trắng thì đổi sang navy, không thêm viền. - Pain hoặc mất mát: dùng tím hoặc navy đậm. Payoff: dùng vàng. **Cấm:** đỏ (kể cả cho "lỗi", "mất tiền"), pastel (mint, peach, lavender), palette 3D stock, trộn màu kiểu oklch ra hồng đỏ. ```css :root { --chatty-navy: #06038d; --chatty-navy-50: #e6e6f4; --chatty-yellow: #fbc80b; --chatty-purple: #5750fe; --chatty-purple-dark-mode: #7570f8; --chatty-aurora-purple: #4f49e7; --chatty-black: #000000; --chatty-gray: #a2a2a2; --chatty-white: #ffffff; --chatty-neutral: #ecedf1; } ``` ### Contrast Tỉ lệ tính từ độ chói tương đối sRGB theo WCAG, làm tròn hai chữ số. | Colour | On white | On navy | Text use | | --- | --- | --- | --- | | Navy `#06038D` | 14.94:1 | 1.00:1 | Có trên nền sáng | | Light navy `#E6E6F4` | 1.24:1 | 12.09:1 | Có trên navy | | Yellow `#FBC80B` | 1.57:1 | 9.51:1 | Không trên nền sáng. Trên navy được | | Purple `#5750FE` | 5.27:1 | 2.83:1 | Có trên trắng. Không trên navy | | Black `#000000` | 21.00:1 | 1.41:1 | Có trên trắng | | Gray `#A2A2A2` | 2.55:1 | 5.85:1 | Không trên nền sáng, chỉ accent icon và vạch chia | | White `#FFFFFF` | 1.00:1 | 14.94:1 | Có trên navy | | Neutral light `#ECEDF1` | 1.17:1 | 12.77:1 | Có trên navy | Purple dark mode `#7570F8`: 3.87:1 trên trắng, 4.47:1 trên `#161B22`. Không dùng làm chữ thường trên các nền này. ### Aurora Nguồn: hero chatty.net, component `PageAuroraBg.tsx`. - Nền trắng. - Đốm vàng `#FBC80B` góc trên trái, đốm tím `#4F49E7` góc dưới phải. Đốm là hình hữu cơ, không phải hình tròn. - Blur khoảng 170 tới 194px. - Lớp noise: SVG `feTurbulence type="fractalNoise" baseFrequency="0.4" numOctaves="3"`, opacity 0.2. - Đáy fade về trắng. - Chữ trên aurora: navy, điểm nhấn tím. ### Site backgrounds Nền trắng + `radial-gradient` vàng `rgba(251,200,11,.30)` ở một góc + `radial-gradient` tím `rgba(87,80,254,.22)` ở góc đối diện. Không tô gradient đậm phủ kín card. ### Gradients | Name | CSS | Use | | --- | --- | --- | | Navy depth | `linear-gradient(180deg, #06038D 40%, #030077 91%)` | Nền banner tối, hero tối | | Yellow to Purple | `linear-gradient(180deg, #FBC80B 0%, #5750FE 100%)` | Chỉ cho icon preset gradient hoặc mảng nhỏ. **Không phủ kín nền** | | Grey to Navy fade | `linear-gradient(180deg, rgba(217,217,217,0) 0%, #06038D 100%)` | Phủ mờ lên ảnh | | Navy deep | `linear-gradient(180deg, #06038D 0%, #02005D 100%)` | Card mascot, section tối | ### Blur | Scale | Use | | --- | --- | | 20px | Bóng nhẹ | | 55px | Glow phần tử | | 200px | Glow nền nhỏ | | 500px | Glow nền lớn | | 700 tới 1089px | Mesh hero | Dùng 1 trong các mức: 20px (bóng nhẹ), 55px (glow phần tử), 200px (glow nền nhỏ), 500px (glow nền lớn), 700 tới 1089px (mesh hero). Blur từ 500px chỉ dùng cho hero và landing, không dùng cho ảnh social nhỏ hơn 1080x1080. ### Avoid - Gradient tự chế, góc 135deg nhiều stop, radial vàng "glow góc" kiểu template. - Nền navy phẳng cho ảnh social (Thu đã bác). Nền social dùng aurora, nền sáng hoặc nền tối có noise. - Hạt sáng, sao, chấm bay. Ảnh nền AI sinh. Ảnh stock người mẫu cười cầm laptop. Nguồn: [brand-kit: brand-guidelines.agent.md §2](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-brand-guidelines.agent.md?v=1795057578). Nguồn: [brand-kit: brand-guidelines.agent.md §3](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-brand-guidelines.agent.md?v=1795057578). ## Typography ```clash Chat. Smile. Buy. Aa Bb 0123 ``` ![Specimen Clash Display và body từ Figma](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-typography.webp?v=1795057424) Ảnh từ Figma 2025. Clash Grotesk và Inter trong ảnh là luật cũ, đã được General Sans thay thế trong bản agent. ```general-sans Chatty recommends the right product. Chatty adds it to the cart. Chatty brings shoppers back. ``` | Role | Font | Weight | | --- | --- | --- | | Tiêu đề, số lớn | Clash Display | 500 Medium (ưu tiên), 600 Semibold, 700 Bold cho hero | | Mọi chữ còn lại: body, nhãn, caption, nút | General Sans | 400, 500, 600 | - Tối đa 2 font mỗi ấn phẩm. - **Inter đã bỏ.** Bản 2025 ghi Inter và Clash Grotesk cho body. Luật mới là General Sans. - Không set body bằng Clash Display. Clash chỉ dành cho tiêu đề. - Thu thấy Clash Semibold hơi thô. Mặc định dùng Medium. - **Tiếng Việt:** Clash Display thiếu toàn bộ nguyên âm có dấu (ơ, ư, ạ, ế...). Chữ tiếng Việt không được set Clash. General Sans chưa kiểm đủ dấu, nên dùng Inter hoặc `system-ui` cho tiếng Việt. - **Trang chatty.net (trang chủ):** Clash chỉ cho H1. H2, số lớn, CTA, footer dùng General Sans 600, `letter-spacing: -0.03em`. - Cấm: Google Sans, Poppins, Montserrat, Roboto, Open Sans, font viết tay, serif trang trí. - Nguồn font: Fontshare (license miễn phí cả dùng thương mại). File: `chatty.net/public/fonts/`. ```css font-family: "Clash Display", system-ui, sans-serif; /* tiêu đề tiếng Anh */ font-family: "General Sans", system-ui, sans-serif; /* body */ ``` Tiếng Việt: Clash Display thiếu nguyên âm có dấu. Chữ tiếng Việt dùng Inter hoặc system-ui. Don't: Chữ “Chào bạn” bằng Clash sẽ rơi về font dự phòng. Nguồn: [brand-kit: brand-guidelines.agent.md §4](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-brand-guidelines.agent.md?v=1795057578). ## Icons ![Ba preset icon filled hai tông của Chatty](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-icons.webp?v=1795057405) Ảnh từ Figma. Chờ SVG để có lưới icon tải riêng. - Kiểu: **filled 2D, 2 tông** (1 màu chính + 1 màu accent). Không line-art outline, không bóng, không 3D, không gloss. Góc bo mềm. ViewBox 80x80. - 3 preset, không tự đổi màu: | Preset | Colours | Use | | --- | --- | --- | | Gradient | Yellow `#FBC80B` + Purple `#5750FE` | Chỗ cần nổi bật, CTA, tính năng quan trọng | | Đen xám | Black `#000000` + Gray `#A2A2A2` | Nền sáng, bối cảnh trung tính | | Trắng xám | White `#FFFFFF` + Gray `#A2A2A2` | Nền tối, nhất là navy | - Một màn hình hoặc một ấn phẩm chỉ dùng 1 preset. - Bộ icon hiện có: cart-check, bag, discount-tag, store, box, gift, tag-arrow, chat, scan. Xem `icons.png`. - Cấm: icon Flaticon gradient, Iconscout 3D, Freepik 3D, icon do AI sinh. Nguồn: [brand-kit: brand-guidelines.agent.md §6](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-brand-guidelines.agent.md?v=1795057578). ## Illustration **Bong bóng chat** (lấy từ logo) là yếu tố chính. Dùng nhiều hình dạng và cỡ cho sinh động, nhưng phải cùng một họ. Xem `illustrative-elements.png`. **Pattern động** (`custom-dynamic.png`): - Dùng icon mắt và bong bóng chat làm pattern. - Trong sản phẩm số, pattern dùng nhẹ, không hiện trọn hình. - Pattern mắt giữ trừu tượng và làm mờ. - Logo luôn đặt trên pattern. **Minh hoạ tính năng** (`illustrating-functionality.png`): - Màu chính là vàng, navy, trắng. Vàng kéo mắt, navy và trắng tạo khung. - Bố cục gọn, ít phần tử, để tính năng là trọng tâm. - Dùng cho widget chat, AI trả lời, product card... - Ảnh UI nguồn nhỏ thì dựng lại bằng HTML/CSS cho nét, không phóng ảnh chụp. **Tính năng + thông điệp** (`illustrating-functionality-messaging.png`): - Ghép banner, ảnh, ad copy với minh hoạ tính năng. Minh hoạ là trọng tâm. - Dùng cho campaign, social ads, banner. Có thể trộn ảnh người thật với UI sản phẩm. **Mockup khung chat Chatty** (đặt trên nền Chatty): - Khách bên trái: avatar tròn nhỏ, bong bóng tím nhạt `#C9C7FB`, chữ đen. - Chatty bên phải: bong bóng xám nhạt `#EEEEF3`, chữ đen, avatar `logo/icon-white-gradient-bg.png`, dưới avatar ghi "Chatty AI" màu navy. - Khung trắng, bo góc lớn, bóng nhẹ. **Widget đặt trên store của khách** (preview, demo, dựng lại store): để trung tính. Không logo Chatty, không tím Chatty, chữ gần đen `#111`, nhãn bot là " assistant". **Sticker:** được dùng nhưng không trẻ con. Font đi kèm vẫn phải chắc, chuyên nghiệp. ![Bong bóng chat từ logo](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-illustrative-elements.webp?v=1795057420) Ảnh Figma 2025 có sao lấp lánh; luật 2026 cấm sao (mục 8). Dùng bong bóng, bỏ sao. ![Pattern mắt và bong bóng trừu tượng](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-custom-dynamic.webp?v=1795057400) ![Minh hoạ tính năng Chatty](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-illustrating-functionality.webp?v=1795057415) ![Minh hoạ tính năng kết hợp thông điệp](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-illustrating-functionality-messaging.webp?v=1795057410) ### AI slop Thu đã bác các kiểu dưới đây trên ấn phẩm thật. Gặp là sửa. | Don't | Do | | --- | --- | | Pill, chip, bong bóng bọc tiêu đề hoặc nhãn ("FREE GUIDE", "STEP 1", "After Black Friday") | Chữ trơn, navy, không nền | | Nhãn IN HOA cỡ nhỏ giãn chữ ("REASON 01", "ASSISTED REVENUE") | Viết thường kiểu câu ("Assisted revenue"). Đánh số thì viết số bằng font tiêu đề | | Gạch chân hoặc marker vàng dưới số | Nhấn bằng cỡ chữ, màu, khoảng trống | | Vòng elip vẽ tay để khoanh | Khung chữ nhật bo góc vàng `#FBC80B` (bo không quá 12px trên ảnh blog) | | Chữ có viền (`-webkit-text-stroke`) | Chữ phẳng, cần nổi thì đổi màu nền hoặc màu chữ | | Em dash (U+2014) và middle dot (U+00B7) | Tách câu, dấu phẩy, dấu hai chấm, hoặc " - " | | Thẻ kính, sao 3D, số hình cầu, halo tròn to | Phẳng, 2D | | Accent bar ngắn kèm nhãn kiểu editorial | Bỏ | | Nhiều chữ nhỏ: dòng nguồn, chú thích phụ, nhãn "sample" | Mỗi ảnh 1 điểm nhìn. Nguồn để ở caption | | Mọi loại bài dùng y một bố cục | Mỗi loại bài có bố cục riêng | | Mockup điện thoại có viền đen dày, tai thỏ, camera, nghiêng 3D | Màn trắng bo góc khoảng 52px, viền trong `#E6E6F4` 2px, máy đứng thẳng | Lấy cảm hứng từ mẫu bên ngoài chỉ ở mức bố cục và phối cảnh. Không lấy chất liệu (kính, glow, sao). Nguồn: [brand-kit: brand-guidelines.agent.md §7](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-brand-guidelines.agent.md?v=1795057578). Nguồn: [brand-kit: brand-guidelines.agent.md §8](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-brand-guidelines.agent.md?v=1795057578). ## Voice **Tagline thương hiệu:** "The #1 AI Sales Agent for eCommerce". Dòng "The AI-first chat platform built for eCommerce sales" đã bỏ, không dùng. **Câu giới thiệu 25 chữ (dùng sẵn):** > Chatty is the AI sales agent for Shopify stores. It recommends the right product, adds it to the cart and brings shoppers back, so you sell more. **Cách gọi:** - Chatty là **AI sales agent**, không phải chatbot. Phép thử: thay "Chatty" bằng "a chatbot" mà câu vẫn đúng thì câu đó chưa định vị. - Động từ chính là việc bán: recommends, adds to cart, brings shoppers back. Không lấy "answers questions" làm động từ chính. - Người của merchant gọi là "your team", không gọi "human agents". **Giọng:** Clear, Modern, Friendly, Approachable, Simple, Trustworthy. - Rõ, hiện đại: bố cục thoáng, không nhồi chữ. - Thân thiện, dễ gần: bong bóng chat, mascot, sticker (không trẻ con). - Đơn giản, đáng tin: font tiêu đề chắc, số có nguồn. **Câu khẩu hiệu phụ:** "Chat. Smile. Buy." Nguồn: [brand-kit: brand-guidelines.agent.md §1](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-brand-guidelines.agent.md?v=1795057578). ## Not yet defined Các trang dưới đây có trong Figma nhưng chưa chép. Gặp việc cần các phần này thì hỏi Thu, không tự đặt luật. - Brand look & feel (trang moodboard tổng) - Partnership: đặt logo Chatty cạnh logo đối tác - Photography: ảnh nên dùng và ảnh không nên dùng - Logo: vùng trống tối thiểu, kích thước tối thiểu Hỏi Thu Le trước khi đặt luật. Nguồn: [brand-kit: brand-guidelines.agent.md §10](https://cdn.shopify.com/s/files/1/0959/0128/6675/files/guide-20261119-brand-guidelines.agent.md?v=1795057578). --- # Ad referral Thẻ nguồn quảng cáo của tin nhắn trong inbox. ## Key rules - Thẻ chỉ render khi có dữ liệu quảng cáo. - Element `chatty-ad-referral` ở mục Standard là chuẩn chatty-ui port theo; các mục theo surface mô tả component React đang chạy. ## Use when / Avoid Hiển thị ngữ cảnh quảng cáo của hội thoại. ### Use instead | Component | Use when | | --- | --- | | `AdReferralBlock` | Hiển thị ngữ cảnh quảng cáo của hội thoại. | | `button` | Caller sở hữu tương tác liên quan. | ## Live preview Example (Standard) — Card chỉ có caption, và card có thumbnail, link bài đăng và chi tiết thu gọn. ```html Summer collection
Explore our collection
Canvas tote bag
Carry everything, every day. Canvas tote bag
``` Example (Standard) — Card đã mở rộng: caption đầy đủ và ảnh chi tiết. ```html Canvas tote bag
Carry everything, every day. Canvas tote bag
``` Example (Current (React), being replaced) — Thẻ thật với dữ liệu cục bộ, không có media ngoài. ```jsx import React from 'react'; import {AdReferralBlock} from '@assets/pages/InboxManagement/v2/blocks/AdReferralBlock.jsx'; import '@assets/pages/InboxManagement/v2/styles.scss'; export function Card() { return text}} />; } ``` ## Standard Example (Standard) — Card chỉ có caption, và card có thumbnail, link bài đăng và chi tiết thu gọn. ```html Summer collection
Explore our collection
Canvas tote bag
Carry everything, every day. Canvas tote bag
``` Prototype (cùng `ad-referral.styles.js`) là chuẩn: chatty-ui port 1:1, và `chatty-ui/custom-elements.json` sinh từ chính prototype. Caption, thumbnail và phần chi tiết (media, sản phẩm) đi qua slot. Chưa inbox dùng element thật; mục Admin bên dưới mô tả React đang chạy. ### Element | Element | Module | | --- | --- | | `chatty-ad-referral` | @avada/chatty-ui/elements/ad-referral.js | ### API | Kind | Name | Type | Default | Description | | --- | --- | --- | --- | --- | | attribute | `heading` | string | `''` | Nhãn kênh, ví dụ Facebook ad, Instagram ad, Clicked your ad. | | attribute | `href` | string | `''` | URL bài đăng; chỉ http(s), URL khác thì ẩn link. | | attribute | `link-label` | string | `'View post'` | Chữ của link bài đăng. | | attribute | `toggle-label` | string | `'Ad details'` | Tên truy cập của nút mở rộng. | | attribute | `expanded` | boolean | `false` | Mở caption đầy đủ và phần chi tiết; ẩn thumbnail. | | event | `toggle` | Event | – | expanded đổi từ nút mở rộng. | | event | `click` | MouseEvent | – | Kích hoạt native của nút mở rộng. | | slot | default | – | – | Caption: tiêu đề và nội dung quảng cáo. | | slot | `thumb` | – | – | Thumbnail, ẩn khi mở rộng. | | slot | `details` | – | – | Media và sản phẩm, hiện khi mở rộng. | | part | `base` | – | – | Khung card. | | part | `label` | – | – | Nhãn kênh. | | part | `link` | – | – | Link bài đăng. | | part | `caption` | – | – | Caption bị kẹp khi thu gọn. | | part | `toggle` | – | – | Nút mở rộng; chỉ hiện khi có chi tiết hoặc caption bị kẹp. | | part | `details` | – | – | Vùng chi tiết. | | css-property | `--chatty-ad-referral-radius` | – | – | Bo góc. | | css-property | `--chatty-ad-referral-background` | – | – | Nền. | ## Admin ### Import / element | Component / element | Import / file | Scope root | | --- | --- | --- | | `AdReferralBlock` | @assets/pages/InboxManagement/v2/blocks/AdReferralBlock.jsx | .inbox-v2 | ### Anatomy | Part | Element | | --- | --- | | 1 | Thumbnail tùy chọn, nhãn, nội dung, nút mở rộng và media. | ### Placement / order | Context | Order | | --- | --- | | Caller | Theo thứ tự markup của component. | ### Props | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `block` | object | adReferral và i18n | Caller | Không có adReferral thì trả null. | ### Sizes | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | Component | Theo nội dung | 8px | 8px | Theo token | body-small | Nút native | Grid fit-content | ### Tokens | Part | Token | Light | Dark | | --- | --- | --- | --- | | Nền | Theo style inbox | Theo style inbox | No Dark skin | ### States | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Mở rộng | Có media hoặc caption bị cắt | Hiện chi tiết khi nhấn. | aria-expanded | ### Behaviour | Interaction | Result | | --- | --- | | Toggle | Đổi expanded và dừng sự kiện hàng. | ### Copy | String | i18n key | Where | | --- | --- | --- | | Ad details | Ad details | Nhãn nút mở rộng | ### Source | File | Evidence | | --- | --- | | | Public API | | | Markup | | | Caller | ## Do / Don't Do: dùng API của surface hiện tại. Don't: thay hành động của caller bằng hành vi giả định. ## Accessibility | Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio | | --- | --- | --- | --- | --- | | Admin | Nút có tên Ad details và aria-expanded | Nút native nhận Tab, Enter, Space | Không có live region | Theo style inbox | ## Target ```target | Surface | Now | Target | Source | | --- | --- | --- | --- | | Admin | Thẻ React trong thread của inbox | Not available — new build follows Target. Registry block của `chatty-message` (đợt C) ánh xạ block `ad-referral` sang element `chatty-ad-referral`, không có tag `chatty-block-*` riêng; dữ liệu đi qua property, không qua attribute; block không biết thì ẩn. | [MDN: Web Components](https://developer.mozilla.org/en-US/docs/Web/API/Web_components) | | Admin | Component React theo surface | Not available — new build follows Target. Port `chatty-ad-referral` từ mục Standard rồi chuyển caller từng surface. | | ``` - [MDN: Web Components](https://developer.mozilla.org/en-US/docs/Web/API/Web_components) --- # Answer error Thông báo lỗi an toàn cho khách và hành động Retry do host xử lý. ## Key rules - Element prototype là chuẩn để chatty-ui port theo. - Host giữ dữ liệu, dịch nhãn và xử lý event; preview chỉ dùng dữ liệu cục bộ. ## Use when / Avoid Dùng trong cuộc trò chuyện. Tránh nối trực tiếp element với API của shop. ### Use instead | Component | Use when | | --- | --- | | `AnswerError` | Implementation React đang chạy. | | Element prototype | Consumer chuyển sang custom element. | ## Live preview Example (Current (React), being replaced) — Component React thật; dữ liệu fixture, không gửi request. ```jsx import React, {useState} from 'react'; import {AnswerError} from '@avada/chatty-ui/canonical/AnswerError.jsx'; export function Retry({surface}) { const [retried, setRetried] = useState(false); return (
text} onRetry={() => setRetried(true)} /> {retried &&

Retry requested locally.

}
); } ``` Example (Current (React), being replaced) — Component React thật; dữ liệu fixture, không gửi request. ```jsx import React, {useState} from 'react'; import {AnswerError} from '@avada/chatty-ui/canonical/AnswerError.jsx'; export function Retry({surface}) { const [retried, setRetried] = useState(false); return (
text} onRetry={() => setRetried(true)} /> {retried &&

Retry requested locally.

}
); } ``` ## Standard Example (Standard) — Element prototype với token trung tính. ```html ``` Admin chỉ dùng trong inbox và chỉ light; admin-dark là N/A. Surface chưa có React tương ứng ghi Not available bên dưới. ### Element | Element | Module | | --- | --- | | `chatty-answer-error` | @avada/chatty-ui/elements/answer-error.js | ### API | Kind | Name | Type | Default | Description | | --- | --- | --- | --- | --- | | attribute | `label` | string | `'Something went wrong while preparing the answer.'` | Translated safe error message. | | attribute | `retry-label` | string | `'Try again'` | Translated retry action. | | attribute | `disabled` | boolean | `false` | Prevents a duplicate retry while pending. | | event | `chatty-retry` | CustomEvent<{}> | Not available | Requests another answer attempt. | | event | `click` | MouseEvent | Not available | Native retry button click. | | part | `base` | Not available | Not available | Error alert. | | part | `retry` | Not available | Not available | Retry button. | ## Classic Token values dưới đây là fallback cục bộ; theme của caller có thể override. ### Import / element | Component / element | Import / file | Scope root | | --- | --- | --- | | `AnswerError` | @avada/chatty-ui/canonical/AnswerError.jsx | AnswerError | ### Anatomy | Part | Element | | --- | --- | | 1 | AnswerError | ### Placement / order | Context | Order | | --- | --- | | Conversation | Caller supplies surrounding content | ### Props | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `onRetry` | See source | Caller supplied | See source | Retry callback | ### Sizes | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | Retry base | min-height 44px | 12px | 6px | 999px | button-label | 44px | Base CSS; caller may override | ### Tokens | Part | Token | Light | Dark | | --- | --- | --- | --- | | Error text | `--chatty-contact-muted` | Fallback #6b6b6b | Fallback #6b6b6b | | Retry ink | `--chatty-contact-fg` | Fallback #1f1f1f | Fallback #1f1f1f | ### States | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Error | Answer fails | Error label and Retry visible | role alert | ### Behaviour | Interaction | Result | | --- | --- | | Retry | Calls onRetry | ### Copy | String | i18n key | Where | | --- | --- | --- | | Caller translated | Not available | AnswerError | ### Source | File | Evidence | | --- | --- | | | Owning React implementation. | ## AI Mode Token values dưới đây là fallback cục bộ; theme của caller có thể override. ### Import / element | Component / element | Import / file | Scope root | | --- | --- | --- | | `AnswerError` | @avada/chatty-ui/canonical/AnswerError.jsx | AnswerError | ### Anatomy | Part | Element | | --- | --- | | 1 | AnswerError | ### Placement / order | Context | Order | | --- | --- | | Conversation | Caller supplies surrounding content | ### Props | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `onRetry` | See source | Caller supplied | See source | Retry callback | ### Sizes | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | Retry base | min-height 44px | 12px | 6px | 999px | button-label | 44px | Base CSS; caller may override | ### Tokens | Part | Token | Light | Dark | | --- | --- | --- | --- | | Error text | `--chatty-contact-muted` | Fallback #6b6b6b | Fallback #6b6b6b | | Retry ink | `--chatty-contact-fg` | Fallback #1f1f1f | Fallback #1f1f1f | ### States | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Error | Answer fails | Error label and Retry visible | role alert | ### Behaviour | Interaction | Result | | --- | --- | | Retry | Calls onRetry | ### Copy | String | i18n key | Where | | --- | --- | --- | | Caller translated | Not available | AnswerError | ### Source | File | Evidence | | --- | --- | | | Owning React implementation. | ## Do / Don't Do: giữ host làm owner của dữ liệu. Don't: gửi lại chỉ vì element render. ## Accessibility | Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio | | --- | --- | --- | --- | --- | | Classic | Alert | Tab to Retry; Enter or Space activates | Alert | See neutral token preview | | AI Mode | Alert | Tab to Retry; Enter or Space activates | Alert | See neutral token preview | --- # Avatar Avatar tròn của kit chung; Classic chỉ dùng nó cho ảnh sản phẩm và badge số lượng trong đơn hàng. ## Key rules - Dùng `Avatar` với `AvatarFallback` từ `@avada/chatty-ui`; mặc định `width: 36` và `height: 36` (số thuần của React style), bo `50%`. - Order group ghi đè: container ảnh sản phẩm bo 8px, viền 1px; badge số lượng 16px. - Đặt `alt` bằng tên sản phẩm hoặc chuỗi rỗng; root `Avatar` là `div`, không có role ảnh. - Element `chatty-avatar` ở mục Standard là chuẩn chatty-ui port theo; các mục theo surface mô tả component React đang chạy. ## Use when / Avoid Dùng khi cần một khung tròn cố định cho ảnh, chữ hoặc biểu tượng nhỏ. Kit không có trạng thái tải ảnh lỗi, nên caller tự chọn ảnh hoặc fallback. Classic hiện chỉ có caller là nhóm ảnh sản phẩm trong đơn hàng; không có avatar người gửi trong luồng chat Classic dùng component này. ### Use instead | Component | Use when | | --- | --- | | `Avatar` | Khung tròn mặc định `width: 36` chứa ảnh hoặc `AvatarFallback`. | | `img` | Ảnh sản phẩm đặt trực tiếp trong `Avatar`, caller tự cấp `alt`. | | `Badge` | Nhãn trạng thái hoặc số đứng cạnh đối tượng, không phải khung ảnh tròn. | ## Live preview Example (Standard) — Element chatty-avatar: size sm, md, lg với chữ viết tắt và ảnh. ```html AL AL AL Blue mug ``` Example (Current (React), being replaced) — Avatar mặc định với AvatarFallback và AvatarImage; dữ liệu cục bộ. ```jsx import React from 'react'; import AvatarGroup from '@scripttag/v1/MuiPages/AvatarGroup'; import {Avatar, AvatarFallback, AvatarImage} from '@avada/chatty-ui/components/avatar.js'; const avatars = ['/fixtures/avatar-alex.svg', '/fixtures/avatar-minh.svg']; export function Catalogue() { return (
AB

Fallback

Image

); } ``` Example (Current (React), being replaced) — AvatarGroup thật của đơn hàng; JSX được trích đúng caller. ```jsx import React, {useMemo, useState} from 'react'; import {Avatar, AvatarFallback} from '@avada/chatty-ui'; import {sizedShopifyImage} from '@scripttag/platform/helpers/shopifyImage.js'; const MAX_PRODUCT_IMAGES_TO_SHOW = 4; export default function AvatarGroup({lineItems, i18n}) { const surplusCount = lineItems.length - MAX_PRODUCT_IMAGES_TO_SHOW; const [showAll, setShowAll] = useState(false); const lineItemsToShow = useMemo(() => { if (showAll) return lineItems; return surplusCount > 0 ? lineItems.slice(0, 3) : lineItems; }, [lineItems, showAll, surplusCount]); return (
{lineItemsToShow.map(({image, quantity, title}, index) => (
{title
{quantity}
))} {surplusCount > 0 && !showAll && ( setShowAll(prev => !prev)}> +{surplusCount + 1} {i18n('more')} )}
); } ``` Example (Standard) — Availability fixture: online, offline, break, holiday và null (không có dot). ```js import '@avada/chatty-ui/tokens/tokens.css'; // Standard: the chatty-avatar prototype chatty-ui ports from (chatty-ui/src/elements/avatar.js). import {html} from 'lit'; import '@avada/chatty-ui/elements/avatar.js'; export function Status() { return html`${['online', 'offline', 'break', 'holiday', null].map(status => html`S`)}`; } ``` ## Standard Example (Standard) — Element chatty-avatar: size sm, md, lg với chữ viết tắt và ảnh. ```html AL AL AL Blue mug ``` Prototype (cùng `avatar.styles.js` và ) là chuẩn: chatty-ui port 1:1 các file này, và `chatty-ui/custom-elements.json` sinh từ chính prototype. Chưa surface nào dùng element thật; các mục theo surface bên dưới mô tả React đang chạy. ### Element | Element | Module | | --- | --- | | `chatty-avatar` | @avada/chatty-ui/elements/avatar.js | ### API `status`: online / offline / break / holiday hoặc null (mặc định). Dot 9px ở góc avatar, màu từ STATUS_DOT_COLOR của React; null không render node. Host cấp availability đã resolve. | Kind | Name | Type | Default | Description | | --- | --- | --- | --- | --- | | attribute | `size` | sm, md, lg | `'md'` | Kích thước khung; md bằng khung mặc định của React. | | attribute | `label` | string | `''` | Tên truy cập khi slot là chữ viết tắt; ảnh dùng alt của img. | | attribute | `status` | online, offline, break, holiday, null | null | Availability; null ẩn dot. | | part | `status` | – | – | Dot availability ở góc. | | slot | default | – | – | img (cover) hoặc chữ viết tắt, icon fallback. | | part | `base` | – | – | Khung tròn. | | css-property | `--chatty-avatar-size` | – | – | Kích thước khung; thắng size. | | css-property | `--chatty-avatar-radius` | – | – | Bo góc; mặc định tròn. | | css-property | `--chatty-avatar-background` | – | – | Nền fallback sau chữ viết tắt. | ## Classic ### Import / element | Component / element | Import / file | Scope root | | --- | --- | --- | | `Avatar` | @avada/chatty-ui | .chatty-widget > #Avada-FAQ_Widget > .Avada-Faqs_Popup | | `AvatarFallback` | @avada/chatty-ui | .chatty-widget > #Avada-FAQ_Widget > .Avada-Faqs_Popup | | `AvatarImage` | @avada/chatty-ui | .chatty-widget > #Avada-FAQ_Widget > .Avada-Faqs_Popup | ### Anatomy | Part | Element | | --- | --- | | 1 | Root `div` của `Avatar`, nhận `className`, `style` và props khác. | | 2 | `img` của `AvatarImage` hoặc `img` do caller đặt trực tiếp. | | 3 | `AvatarFallback`: `div` căn giữa chữ hoặc số, đặt trong `Avatar`. | ### Placement / order | Context | Order | | --- | --- | | Nhóm ảnh đơn hàng | Với mỗi sản phẩm: `Avatar` chứa `img`, rồi wrapper badge tuyệt đối ở top -4px, right -4px chứa `Avatar` số lượng. | | Nhóm ảnh đơn hàng | Tối đa 4 ảnh; nếu nhiều hơn, hiện 3 ảnh rồi link `more` mở toàn bộ. | ### Props | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `className` | string | CSS classes | undefined | Áp lên root `Avatar`. | | `style` | object | CSS declarations | undefined | Gộp sau style mặc định nên ghi đè được kích thước. | | `src` | string | URL ảnh | undefined | Chỉ có trên `AvatarImage`. | | `alt` | string | Chuỗi mô tả hoặc rỗng | undefined | Chỉ có trên `AvatarImage`; caller đặt tên sản phẩm hoặc chuỗi rỗng. | | `variant` | string | rounded | Caller | Caller truyền `variant` nhưng `Avatar` chỉ chuyển nó vào `div` qua props. | ### Sizes | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | default | `height: 36` | Không có | Không khai báo | `50%` | `fontSize: '0.875rem'`, `fontWeight: 500` | Không tương tác | Không có override theo viewport | | Order container | `height: 36` (không override) | Không có | 12px giữa các item | 8px | Không có chữ | Không tương tác | `!important` trong scope popup | | Order quantity badge | 16px | Không có | Không khai báo | `50%` (inherit từ default) | `heading-small`; `font-size: inherit` | Không tương tác | `!important` trong scope popup | | Order badge wrapper | 20px | Không có | Không khai báo | `50%` | Không có chữ | Không tương tác | Vị trí tuyệt đối top -4px, right -4px | ### Tokens | Part | Token | Light | Dark | | --- | --- | --- | --- | | Container border | `border` | 1px solid #e3e3e3 | `border-color`: transparent | | Badge fill | `background-color` | #707070 | #6c6c6c | | Badge text | `color` | white | white | | Badge wrapper fill | `background` | white | #433f3f | ### States | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Default | Render | `overflow: hidden`; `flexShrink: 0` giữ khung tròn không bị co. | Không thêm ARIA trên root | | Dark | Theme | Container viền transparent; badge và wrapper đổi nền theo Tokens. | Không thêm ARIA | | Image | Có `alt` | `AvatarImage` giữ `aspectRatio: '1/1'`, chiều cao và rộng 100%. | `alt` do caller đặt | ### Behaviour | Interaction | Result | | --- | --- | | Ảnh lỗi | Không có state tải hoặc lỗi; `AvatarImage` và `AvatarFallback` là hai phần tử độc lập, caller quyết định hiển thị. | | Click | Không có handler; root là `div`. | | Số lượng | Caller truyền `quantity` làm nội dung của `AvatarFallback`. | ### Copy | String | i18n key | Where | | --- | --- | --- | | Tên sản phẩm | Caller-owned | `alt` của `img` (`title`), rỗng khi thiếu | | Số lượng | Caller-owned | `AvatarFallback` (`quantity`) | ### Source | File | Evidence | | --- | --- | | | API và style mặc định | | | Caller duy nhất của Classic | | | Override trong scope popup | ## Do / Don't Do: đặt `alt` bằng tên sản phẩm và để `AvatarFallback` giữ số lượng. Don't: dùng root `Avatar` như nút; nó là `div` không có handler hay role. ## Accessibility | Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio | | --- | --- | --- | --- | --- | | Classic | `div` không role; tên đến từ `alt` của `img` do caller | Không focusable; không có handler | Không có | Chữ `white` trên nền #707070; không có dòng nguồn nào chứng minh tỉ lệ nên không nêu | ## Target ```target | Surface | Now | Target | Source | | --- | --- | --- | --- | | Classic · AI Mode · Admin | Component React theo surface | Not available — new build follows Target. Port `chatty-avatar` từ mục Standard rồi chuyển caller từng surface; Inbox Target đọc token chatty-ui literal theo giá trị 2.0 sau phase 1b; ảnh có thể là `chatty-image` đặt vào slot để lo fallback. | | | Admin | Component Inbox đúng Target chưa ship | Not available — new build follows Target. **Avatar**: 20/28/36px; initials và 6 màu theo tên; ảnh lỗi về initials; Online dot và Channel badge; logo shop radius avatar. Dùng ở 8, 5, 10 và Details khách. Không dùng component Polaris trong Inbox; giữ App Bridge cho phần khung embedded. | [Shopify: Built for Shopify requirements](https://shopify.dev/docs/apps/launch/built-for-shopify/requirements) | ``` ![Inbox Avatar design target](https://chatty-ui-research.avada-tesla-chatty.workers.dev/maps/inbox-target-overview.webp) Ảnh Target từ mock; các trạng thái chưa xuất hiện trong ảnh vẫn là yêu cầu triển khai, không claim đã ship. - [MDN: Web Components](https://developer.mozilla.org/en-US/docs/Web/API/Web_components) --- # Badge Nhãn ngắn của kit chung; Knowledge files bọc nó bằng class và data-tone riêng. ## Key rules - Dùng `Badge` với `variant="outline"` và class `kb-ide__badge`; màu theo `data-tone`. - CSS trang khai báo chữ 11px, weight 500, bo 4px, padding 1px 5px. - `Badge` là `div` không tương tác; nghĩa của status phải nằm trong chữ, không chỉ trong màu. - Element `chatty-badge` ở mục Standard là chuẩn chatty-ui port theo; các mục theo surface mô tả component React đang chạy. ## Use when / Avoid Dùng cho nhãn status ngắn cạnh một đối tượng. Không dùng làm nút và không nhét câu dài. Wrapper `KnowledgeBadge` có trong source nhưng hiện chưa có file nào import nó; các nhãn đang hiện trong màn Knowledge files gọi Polaris `Badge`. ### Use instead | Component | Use when | | --- | --- | | `Badge` | Nhãn status của kit chung, dùng class trang cho màu. | | `Badge` | Màn Knowledge files hiện gọi Polaris `Badge` với `tone`, không phải kit. | ## Live preview Example (Standard) — Element chatty-badge: variant, size và tone; token admin, không màu merchant. ```html New Draft Covered 3 Open Failed Synced Pending Active Not covered ``` Example (Standard) — Element chatty-badge size sm viền như nhãn Knowledge files. ```html Draft Covered Pending Not covered ``` Example (Current (React), being replaced) — Badge outline với class Knowledge files; dữ liệu cục bộ. ```jsx import React from 'react'; import {Badge} from '@avada/chatty-ui/components/badge.js'; export function Status() { return
Covered99+
; } ``` ## Standard Example (Standard) — Element chatty-badge: variant, size và tone; token admin, không màu merchant. ```html New Draft Covered 3 Open Failed Synced Pending Active Not covered ``` Prototype (cùng `badge.styles.js` và ) là chuẩn: chatty-ui port 1:1 các file này, và `chatty-ui/custom-elements.json` sinh từ chính prototype. Chưa surface nào dùng element thật; các mục theo surface bên dưới mô tả React đang chạy. Knowledge files vẫn chuyển sang Polaris theo Target; preview admin-kb chỉ để xem element dưới token admin. ### Element | Element | Module | | --- | --- | | `chatty-badge` | @avada/chatty-ui/elements/badge.js | ### API | Kind | Name | Type | Default | Description | | --- | --- | --- | --- | --- | | attribute | `variant` | primary, secondary, tertiary | `'primary'` | primary nền tone đặc, secondary nền nhạt, tertiary chỉ viền. | | attribute | `tone` | neutral, critical, success, caution | `'neutral'` | Ý nghĩa màu; chữ trong badge vẫn phải tự nói status. | | attribute | `size` | sm, md, lg | `'md'` | Cỡ chữ và padding. | | slot | default | – | – | Chữ của badge. | | part | `base` | – | – | Khung pill. | | css-property | `--chatty-badge-background` | – | – | Nền theo variant và tone. | | css-property | `--chatty-badge-color` | – | – | Màu chữ theo variant và tone. | | css-property | `--chatty-badge-radius` | – | – | Bo góc; mặc định pill. | ## Admin · Knowledge files ### Import / element | Component / element | Import / file | Scope root | | --- | --- | --- | | `Badge` | @avada/chatty-ui/components/badge.js | .kb-ide-page > .kb-ide | ### Anatomy | Part | Element | | --- | --- | | 1 | Root `div` của `Badge` mang class kit, `className` và props. | | 2 | Nội dung `children` trong root; caller cấp chữ. | ### Placement / order | Context | Order | | --- | --- | | Wrapper trang | `KnowledgeBadge` render một `Badge` duy nhất với `children`; không có icon. | ### Props | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `variant` | string | default, secondary, destructive, outline, success, warning | `default` | KnowledgeBadge luôn truyền `outline`. | | `size` | string | sm, default, lg | `default` | KnowledgeBadge không truyền size. | | `className` | string | CSS classes | undefined | Gộp cuối; trang truyền `kb-ide__badge`. | | `data-tone` | attribute | error, conflict, warning, pending, partial, audited, covered, draft | Không có | Trang đổi màu theo attribute; component chuyển qua props. | | `children` | ReactNode | Chữ của caller | undefined | Không giới hạn độ dài hay định dạng số. | ### Sizes | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | kit sm | Theo nội dung | `chatty:px-2` / `chatty:py-0.5` | Không khai báo | `chatty:rounded-full` | `chatty:text-xs` | Không tương tác | Class theo `size` | | kit default | Theo nội dung | `chatty:px-2.5` / `chatty:py-0.5` | Không khai báo | `chatty:rounded-full` | `chatty:text-sm` | Không tương tác | Class theo `size` | | kit lg | Theo nội dung | `chatty:px-3` / `chatty:py-1` | Không khai báo | `chatty:rounded-full` | `chatty:text-base` | Không tương tác | Class theo `size` | | Knowledge files page | `line-height: 1.5` | 1px 5px | Không khai báo | 4px | `font-size: 11px`; weight 500 | Không tương tác | Rule không có media query | ### Tokens | Part | Token | Light | Dark | | --- | --- | --- | --- | | Base text | `--p-color-text-secondary` | #616161 | No Dark skin | | Base fill | `--p-color-bg-surface-secondary` | #f7f7f7 | No Dark skin | | Base border | `--p-color-border-secondary` | #ebebeb | No Dark skin | | error / conflict text | `--p-color-text-critical` | #8e0b21 | No Dark skin | | error / conflict fill | `--p-color-bg-surface-critical` | #fee8eb | No Dark skin | | error / conflict border | `--p-color-border-critical-secondary` | #8e0b21 | No Dark skin | | warning / pending / partial text | `--p-color-text-caution` | #4f4700 | No Dark skin | | warning / pending / partial fill | `--p-color-bg-surface-caution` | #fff8db | No Dark skin | | warning / pending / partial border | `--p-color-border-caution-secondary` | Không khai báo trong Polaris 13.9.5 | No Dark skin | | audited / covered text | `--p-color-text-success` | #014b40 | No Dark skin | | audited / covered fill | `--p-color-bg-surface-success` | #cdfed4 | No Dark skin | | audited / covered border | `--p-color-border-success-secondary` | Không khai báo trong Polaris 13.9.5 | No Dark skin | | draft text | `--p-color-text-link` | #005bd3 | No Dark skin | | draft fill | `--p-color-bg-surface-info` | #eaf4ff | No Dark skin | | draft border | `--p-color-border-info-secondary` | Không khai báo trong Polaris 13.9.5 | No Dark skin | ### States | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Base | Không có `data-tone` | Màu theo Tokens dòng Base | Không thêm ARIA | | error / conflict | `data-tone` = error hoặc conflict | Chữ, nền, viền theo Tokens | `data-tone` attribute | | warning / pending / partial | `data-tone` = warning, pending hoặc partial | Chữ, nền, viền theo Tokens | `data-tone` attribute | | audited / covered | `data-tone` = audited hoặc covered | Chữ, nền, viền theo Tokens | `data-tone` attribute | | draft | `data-tone` = draft | Chữ, nền, viền theo Tokens | `data-tone` attribute | ### Behaviour | Interaction | Result | | --- | --- | | Chữ dài | Rule trang có `width: fit-content` và `flex-shrink: 0`; không có cắt dòng riêng. | | Focus | Kit có class focus ring cho root; root là div, caller không thêm tabindex trong wrapper. | | Count | Component không giới hạn hay định dạng số; `children` hiển thị nguyên. | ### Copy | String | i18n key | Where | | --- | --- | --- | | Caller label | Caller-owned | `children` của wrapper | ### Source | File | Evidence | | --- | --- | | | API và class kit | | | Wrapper trang | | | Style và tone | ## Do / Don't Do: viết status bằng chữ ngắn và để `data-tone` chỉ làm tăng nhận biết. Don't: dùng màu làm dấu hiệu duy nhất; không biến `Badge` thành nút. ## Accessibility | Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio | | --- | --- | --- | --- | --- | | Admin · Knowledge files | div không role; tên là chữ children | Không focusable, không có handler | Không có | Base Measured(#616161 / #f7f7f7 = 5.78:1); error Measured(#8e0b21 / #fee8eb = 8.09:1); warning Measured(#4f4700 / #fff8db = 8.82:1); covered Measured(#014b40 / #cdfed4 = 8.99:1); draft Measured(#005bd3 / #eaf4ff = 5.49:1) | ## Target ```target | Surface | Now | Target | Source | | --- | --- | --- | --- | | Admin · Knowledge files | Viền của tone warning, covered và draft dùng token không khai báo trong Polaris 13.9.5 | Not in code yet — build with the body values. Dùng token viền có khai báo `--p-color-border-caution`, `--p-color-border-success`, `--p-color-border-info`; giữ border 1px solid và radius 4px, không đổi chữ hay nền. | | | Admin · Knowledge files | Badge của kit chung trong Knowledge files | Not available — new build follows Target. Knowledge files không dùng `chatty-*`: chuyển sang Polaris `Badge`, vì trang admin ngoài inbox giữ Polaris. | [Shopify: Built for Shopify requirements](https://shopify.dev/docs/apps/launch/built-for-shopify/requirements) | | Classic · AI Mode · Admin | Component React theo surface | Not available — new build follows Target. Port `chatty-badge` từ mục Standard rồi chuyển caller từng surface; Inbox Target dùng token chatty-ui literal theo giá trị 2.0; gỡ wrapper hiện tại ở phase 1b trước khi chuyển caller. | | | Admin | Component Inbox đúng Target chưa ship | Not available — new build follows Target. **Badge**: neutral/caution; info/success/warning/critical; progress complete/partial/incomplete; 20px, radius tag 6px, badge-label 12px/18px w500. Dùng ở Return customer (10), order badges (15), Verified, Change request, Resolved. Không dùng component Polaris trong Inbox; giữ App Bridge cho phần khung embedded. | [Shopify: Built for Shopify requirements](https://shopify.dev/docs/apps/launch/built-for-shopify/requirements) | ``` ![Inbox Badge design target](https://chatty-ui-research.avada-tesla-chatty.workers.dev/maps/inbox-target-overview.webp) Ảnh Target từ mock; các trạng thái chưa xuất hiện trong ảnh vẫn là yêu cầu triển khai, không claim đã ship. - [Shopify: Built for Shopify requirements](https://shopify.dev/docs/apps/launch/built-for-shopify/requirements) - [MDN: Web Components](https://developer.mozilla.org/en-US/docs/Web/API/Web_components) --- # Banner / callout Target cho Inbox thuần chatty-ui; owner hiện tại là HandoffCard, chưa phải component dùng chung mới. ## Key rules - Admin: phần Current chỉ chỉ ra owner đang dùng; component Inbox dùng chung theo thiết kế nằm ở Target. - Admin: ảnh preview là thiết kế, không chứng minh API hoặc hành vi đã ship. ## Use when / Avoid Dùng để triển khai Banner / callout của Inbox theo Target. Không import tên component Target chưa tồn tại; không coi owner cục bộ là API dùng chung. ### Use instead | Component | Use when | | --- | --- | | HandoffCard | Owner hiện tại của vùng tương ứng; chưa phải Target dùng chung | | Input | Ô nhập thô của kit, chưa có đủ wrapper Target | ## Live preview Example — Target: ảnh chụp mock, xem trạng thái và vùng dùng trong Target; chưa phải implementation. ```jsx import React from 'react'; function Design({asset,name}) { return
{name+'
Target · thiết kế mock, chưa phải implementation. Ảnh không chứng minh mọi trạng thái yêu cầu đã có.
; } export function Banner() { return ; } ``` ## Admin ### Import / element | Component / element | Import / file | Scope root | | --- | --- | --- | | `HandoffCard` | import HandoffCard from '@assets/pages/InboxManagement/Parts/ConverstionDetail/HandoffCard.js'; | Owner cục bộ hiện tại; chưa có scope dùng chung cho component Target | ### Anatomy | Part | Element | | --- | --- | | 1 | Owner hiện tại: HandoffCard; component dùng chung mới chưa có | ### Placement / order | Context | Order | | --- | --- | | Inbox | Theo caller hiện tại; vị trí của component mới nằm ở Target | ### Props | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | Not available | Not available | Not available | Not available | API dùng chung mới chưa có; không tái đặt API của owner | ### Sizes | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | Not available | Not available | Not available | Not available | Not available | Not available | Not available | Not available | ### Tokens | Part | Token | Light | Dark | | --- | --- | --- | --- | | Not available | Not available | Not available | Not available | ### States | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Not available | Not available | Chưa có state contract dùng chung theo Target | Not available | ### Behaviour | Interaction | Result | | --- | --- | | Current owner | Theo logic cục bộ; contract mới xem Target | ### Copy | String | i18n key | Where | | --- | --- | --- | | Not available | Not available | Nhãn do caller hiện tại quản lý | ### Source | File | Evidence | | --- | --- | | | Owner hiện tại; không chứng minh component Target đã có | ## Do / Don't Do: giữ ranh giới giữa code hiện tại và Target khi triển khai. Don't: bịa import hoặc dùng ảnh thiết kế làm bằng chứng API đã ship. ## Accessibility | Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio | | --- | --- | --- | --- | --- | | Admin | Owner hiện tại quản lý | Not available cho component dùng chung mới | Not available | Chưa đo cho component Target | ## Target ```target | Surface | Now | Target | | --- | --- | --- | | Admin | Owner HandoffCard có trong source; component dùng chung đúng Target chưa có | Not available — new build follows Target. **Banner / callout**: tone warning/info; icon; action; bản strip cho thanh mỏng. Dùng ở Hand-off card (27), Language bar (33), Handover bar. Giá trị 2.0 qua token chatty-ui literal; phase 1b gỡ wrapper Polaris trước khi chuyển caller. | ``` Ảnh chỉ chứng minh phần được vẽ trong mock; các trạng thái liệt kê là yêu cầu triển khai, không claim ảnh hoặc code đã có đủ. --- # Button Chọn đúng API và giá trị đang chạy cho Classic, AI Mode, Admin và Knowledge files. ## Key rules - Classic: action chính trong chat dùng `Button` + `Avada-Faqs_Primary-Button` và `Spinner` từ đường import của caller; xem Import / element. - AI Mode: dùng native button với CSS kit; class, kích thước và trạng thái nằm trong bảng AI Mode. - Admin: Polaris ngoài Inbox; Inbox dùng chatty-ui Target 2.0. - Admin · Knowledge files: shared `Button` chịu stylesheet của trang; kích thước đọc ở bảng riêng. - Element `chatty-button` ở mục Standard là chuẩn chatty-ui port theo; các mục theo surface mô tả component React đang chạy, Target giữ thay đổi dự kiến. ## Use when / Avoid Dùng hành động có kết quả rõ ràng. Điều hướng trong nội dung dùng Link; thao tác chỉ có biểu tượng cần tên truy cập. Mỗi surface có owner riêng, không đổi API theo tên nhìn giống nhau. ### Use instead | Component | Use when | | --- | --- | | `Button` | Action của Classic hoặc Knowledge files; không phải API Polaris. | | `a` | Điều hướng khi href có giá trị; disabled native không áp lên anchor. | | `button` | AI Mode CSS kit, không import shared Button. | | `Button` | Admin gọi Polaris, ví dụ WidgetModeCard dùng tertiary. | ## Live preview Example (Standard) — Ma trận variant, size và tone theo surface. ```html

Button variants and sizes

Send Cancel Skip View order Small Large Delete Confirm
``` Example (Standard) — Disabled, loading, link và nhãn truy cập của element. ```html
Disabled Sending Open link ×
``` Example (Standard) — Ma trận variant, size và tone theo surface. ```html

Button variants and sizes

Send Cancel Skip View order Small Large Delete Confirm
``` Example (Standard) — Disabled, loading, link và nhãn truy cập của element. ```html
Disabled Sending Open link ×
``` Example (Standard) — Ma trận variant, size và tone theo surface. ```html

Button variants and sizes

Send Cancel Skip View order Small Large Delete Confirm
``` Example (Standard) — Disabled, loading, link và nhãn truy cập của element. ```html
Disabled Sending Open link ×
``` Example (Current (React), being replaced) — Variants và sizes theo API; default in-chat dùng màu merchant. ```jsx import React from 'react'; import {Button, Spinner} from '@assets/components/ui'; import '@scripttag/v1/MuiComponents/EmailTranscript.scss'; export function Catalogue() { return (

Variants

{['default', 'outline', 'secondary', 'ghost', 'iconOnly', 'destructive'].map(variant => ( ))}

Sizes

{['sm', 'default', 'lg', 'icon', 'auto'].map(size => ( ))}
); } ``` Example (Current (React), being replaced) — Idle, loading và email rỗng; JSX được trích đúng caller EmailTranscript. ```jsx import {Button, Typography, Spinner} from '@assets/components/ui'; ``` Example (Current (React), being replaced) — Các variant và size CSS kit trong một grid. ```jsx import React from 'react'; import '@scripttag/v2/ui/control.scss'; export function Catalogue() { return (

Variants

{['accent', 'glass', 'ghost', 'danger'].map(variant => ( ))}

Sizes

Long label

); } ``` Example (Current (React), being replaced) — Hover/focus, disabled và loading class. ```jsx import React from 'react'; import '@scripttag/v2/ui/control.scss'; export function States() { return (
); } ``` Example (Current (React), being replaced) — Các variant và size Polaris trong một grid. ```jsx import React from 'react'; import {AppProvider, Button} from '@shopify/polaris'; function ButtonTarget() { return
Inbox Target preview and states

Target Button: primary, secondary, tertiary, plain; tone critical; hover, pressed, focus, disabled, loading; slot icon và slot kbd. Admin 28px, radius action full; token chatty-ui theo giá trị 2.0. Dùng ở Assign to me / Resolve / Reopen (32), Send (13), filter pill (7), Done (24), Good/Needs fix.

Inbox Button design target

Ảnh mock chỉ chứng minh phần đã vẽ, không phải API đã ship. Mẫu giá trị Light/Dark ở Colour & elevation.

; } export function Catalogue() { return (

Variants

{['primary', 'secondary', 'tertiary', 'plain', 'monochromePlain'].map(variant => ( ))}

Sizes

{['micro', 'slim', 'medium', 'large'].map(size => ( ))}

Long label

); } ``` Example (Current (React), being replaced) — Disabled, selected, loading, disclosure và URL. ```jsx import React from 'react'; import {AppProvider, Button} from '@shopify/polaris'; function ButtonTarget() { return
Inbox Target preview and states

Target Button: primary, secondary, tertiary, plain; tone critical; hover, pressed, focus, disabled, loading; slot icon và slot kbd. Admin 28px, radius action full; token chatty-ui theo giá trị 2.0. Dùng ở Assign to me / Resolve / Reopen (32), Send (13), filter pill (7), Done (24), Good/Needs fix.

Inbox Button design target

Ảnh mock chỉ chứng minh phần đã vẽ, không phải API đã ship. Mẫu giá trị Light/Dark ở Colour & elevation.

; } export function States() { return (
); } ``` Example (Current (React), being replaced) — Shared variants và sizes dưới override Knowledge files. ```jsx import React, {useState} from 'react'; import {Button} from '@avada/chatty-ui/components/button.js'; export function Catalogue() { return (

Variants

Sizes

{['sm', 'default', 'lg', 'icon', 'auto'].map(size => (
))}
); } ``` Example (Current (React), being replaced) — Hover, focus, disabled và aria-pressed do caller. ```jsx import React, {useState} from 'react'; import {Button} from '@avada/chatty-ui/components/button.js'; export function States() { const [pressed, setPressed] = useState(false); return (
); } ``` ## Standard Example (Standard) — Form transcript có email, Send primary và Cancel secondary; token theo surface. Classic dark: Cancel dùng nền tối; widget đang ship khối trắng. ```js import '@avada/chatty-ui/tokens/tokens.css'; // Standard: the chatty-button prototype chatty-ui ports from (chatty-ui/src/elements/button.js). 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`A${content.sender ?? message.senderName ?? message.senderMeta?.name ?? 'Assistant'}` }; }; return html`
${ mobileSheet ? html`

Example storefront

{ event.currentTarget.textContent = 'Products opened'; }} > Browse products
${surface === 'ai-mode' ? html`` : ''}` : '' }
${headerStart ?? ''} ${surface === 'admin' ? '' : html`S`} ${title ?? (surface === 'admin' ? 'Customer conversation' : strings.header)}${surface === 'admin' ? html`Customer` : status == null ? '' : html`${status === 'online' ? 'Open' : 'Closed'}`} ${headerActions ?? ''} ${ surface === 'admin' ? '' : html` toggle(event, true)} >${IconClose()}` }
${content ?? ''} { 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 } ]); }} >
${ surface === 'admin' ? '' : surface === 'ai-mode' ? html`` : html`` }
`; } import '@avada/chatty-ui/elements/button.js'; export function Standard({surface}) { const store = fixtureStore([ {id: 'transcript', senderType: 'bot', text: 'You can email this conversation to yourself.'} ]); const content = html`
Send Cancel
`; // Keep public Code executable rather than extracting only the static form. return html`${patternShell({surface, store, content})}`; } ``` Prototype Button và các style đi kèm là chuẩn: package được port 1:1 từ prototype, và manifest phần tử được sinh từ cùng nguồn. Chưa surface nào dùng element thật; các mục Classic, AI Mode và Admin bên dưới mô tả React đang chạy. Admin · Knowledge files giữ Polaris. Lớp data-chatty-surface chọn token button riêng cho Classic, AI Mode và Admin; data-chatty-theme chọn Light/Dark. AI Mode dùng sm/md/lg 32/40/48px; radius 10/14/14px. Classic dùng 32/36/40px. Admin giữ size Polaris; large/plain dùng bodyMd, micro plain dùng bodySm, nên medium plain cao 32px theo line box. Token --chatty-button-md-height là baseline theo surface cho size; override --chatty-button-height vẫn đặt chiều cao control trực tiếp (ví dụ action Toast trên touch). ### Element | Element | Module | | --- | --- | | `chatty-button` | @avada/chatty-ui/elements/button.js | ### API | Kind | Name | Type | Default | Description | | --- | --- | --- | --- | --- | | attribute | `variant` | primary, secondary, tertiary, plain | `'secondary'` | Mức nhấn của action; giá trị lạ quay về mặc định. | | attribute | `tone` | neutral, critical, success, caution | `'neutral'` | Ý nghĩa màu của action. | | attribute | `size` | sm, md, lg | `'md'` | Chiều cao và padding; mặc định md. | | attribute | `disabled` | boolean | `false` | Chặn kích hoạt, vẫn nhận focus và báo aria-disabled. | | attribute | `loading` | boolean | `false` | Hiện spinner, báo aria-busy và chặn kích hoạt. | | attribute | `href` | string | `''` | URL http, https, mailto hoặc tel thì render link; URL khác bị bỏ. | | attribute | `label` | string | `''` | Tên truy cập khi nội dung chỉ là biểu tượng. | | attribute | `type` | button, submit, reset | `'button'` | submit và reset gọi form chứa element qua ElementInternals. | | event | `click` | MouseEvent | – | Kích hoạt native; bị chặn khi disabled hoặc loading. | | slot | default | – | – | Nhãn của button. | | slot | `start` | – | – | Nội dung đứng trước nhãn. | | slot | `end` | – | – | Nội dung đứng sau nhãn. | | part | `base` | – | – | Control native (button hoặc a). | | part | `label` | – | – | Vùng chứa nhãn. | | part | `start` | – | – | Vùng chứa slot start. | | part | `end` | – | – | Vùng chứa slot end. | | css-property | `--chatty-button-radius` | – | – | Bo góc. | | css-property | `--chatty-button-plain-bg-hover` | – | – | Plain hover/pressed fill; unset giữ tertiary fill. | | css-property | `--chatty-button-plain-decoration-hover` | – | – | Plain interaction decoration; unset giữ base decoration. | | css-property | `--chatty-button-plain-focus-radius` | – | – | Plain focus radius; unset giữ base radius. | | css-property | `--chatty-button-background` | – | – | Nền theo variant và tone. | | css-property | `--chatty-button-color` | – | – | Màu chữ theo variant và tone. | | css-property | `--chatty-button-border-color` | – | – | Màu viền theo variant và tone. | | css-property | `--chatty-button-height` | – | – | Chiều cao control. | | css-property | `--chatty-button-padding-inline` | – | – | Padding ngang. | | css-property | `--chatty-button-width` | length-percentage, auto | `auto` | Bề rộng control; `100%` giãn hết vùng chứa. | Storefront mở rộng success/caution; Classic critical chưa có caller đang ship. AI Mode accent mặc định `#303030` từ launcher; danger giữ đỏ AA `#dc2626`. ### Variant mapping | chatty-button | Classic | AI Mode | Admin (Polaris) | | --- | --- | --- | --- | | primary | Primary-Button | accent | primary | | secondary | Add to cart; action trong card dùng radius 10px | glass | secondary | | tone=critical | Mở rộng | danger (AA) | primary critical | | tertiary | ghost | ghost | tertiary | | plain | Link hành động | Mở rộng cho link hành động, không gạch chân | plain, không gạch chân | | secondary + tone=success | Mở rộng: nền secondary, chữ xanh | Mở rộng: nền glass, chữ xanh | secondary + tone=success | Đối chiếu component React đang chạy ở từng mục surface bên dưới. ### Intentional differences | Difference | Shipped | Standard | Why | | --- | --- | --- | --- | | Empty icon slots | AI Mode/Polaris không có hai slot icon rỗng | Slot start/end rỗng không chiếm chỗ; bỏ tổng 12px thừa của prototype cũ | Nhãn và padding đúng kích thước nội dung | | One API | Classic default/outline; AI accent/glass/ghost; Polaris variant và tone | Một API primary/secondary/tertiary/plain cộng tone | Caller chọn cùng ý nghĩa theo bảng mapping | | Focus | Storefront outline 2px, offset 2px; Admin thường offset 1px; Polaris plain focus radius 12px và inset | Storefront giữ baseline; Admin dùng chung radius 8px, offset 1px | Focus nhất quán giữa các variant; không phải bản sao mọi caller Polaris | | Disabled contrast | Classic dùng chữ #b5b5b5 trên nền disabled | Giữ paint đang ship | Control không hoạt động được miễn yêu cầu tương phản của WCAG 1.4.3 | | Critical contrast | AI Mode critical #ef4444, chữ trắng chỉ đạt 3.76:1 | #dc2626, chữ trắng đạt 4.83:1 | Đạt 4.5:1 của WCAG 1.4.3; b1-chatty nên port theo | | Reduced motion | AI Mode vẫn press scale khi bật reduced motion | Tắt scale theo tuỳ chọn reduced motion | Tôn trọng tuỳ chọn giảm chuyển động | | Classic secondary in dark | Add to cart là khối trắng trong dark | Classic secondary in dark uses a dark fill instead of a white block (shipped Add to cart is white in dark); hover cũng dùng nền tối | Giữ chữ #eee đọc rõ khi nghỉ và hover | | Success tone | Classic và AI Mode chưa có tone success chung; Admin secondary chữ xanh | Cả ba surface dùng secondary/glass và chữ xanh; storefront Light dùng #014b40 | Cùng mức nhấn, không tạo khối mint; chữ đạt 4.5:1 trên glass kể cả hover/pressed | Quyết định Success và Classic dark ở đây là lựa chọn của bộ chuẩn, chưa phải thay đổi trong widget đang chạy. ## Classic ### Import / element | Component / element | Import / file | Scope root | | --- | --- | --- | | `Button` + `Spinner` | @assets/components/ui | .chatty-widget > #Avada-FAQ_Widget > .Avada-Faqs_Popup | | In-chat primary action: `Button` + `Avada-Faqs_Primary-Button` + `Spinner` | @assets/components/ui | .Avada-Faqs_Popup; class màu merchant của caller | ### Anatomy | Part | Element | | --- | --- | | 1 | Tag native a/button chọn qua `href`. | | 2 | Nội dung `children`; caller thêm icon/spinner. | ### Placement / order | Context | Order | | --- | --- | | In-chat primary action | Caller EmailTranscript đặt action gửi trong form; dùng Button + class Avada-Faqs_Primary-Button, khi loading thay label bằng Spinner. Trong parent .Avada-Faqs_Body--chatDetail_EmailTranscript, EmailTranscript.scss ghi đè height 40px, width 100% và radius 10px. Không có Cancel trong caller này. | | Primitive | Component nhận children, không tự tạo footer hay thứ tự nhiều action. | ### Props | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `variant` | string | default / outline / ghost / iconOnly / secondary / destructive | default | Fill và interaction utility. | | `size` | string | default / sm / lg / icon / auto | default | Không tự tăng box trên mobile. | | `disabled` | boolean | true / false | undefined | Native button nhận attribute; anchor không nhận disabled. | | `href` | string | URL | undefined | Truthy đổi Tag thành a. | | `iconOnly` | boolean | true / false | undefined | Ép variant iconOnly và size icon; inline background/border/outline none. | | `noBorder` | boolean | true / false | undefined | Inline border none. | | `className` | string | CSS classes | undefined | Gộp cuối utility list. | | `style` | object | CSS declarations | undefined | Merge cuối, có thể override inline icon/noBorder. | | `children` | ReactNode | Caller content | undefined | Không có copy hay i18n mặc định. | | `props` | attributes / handlers | Native attrs, onClick, aria-\* | Caller | Spread vào Tag; caller đặt type cho form. | ### Sizes | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | sm | Derived(32px = h-8 × 4px) | 0 / Derived(12px = px-3 × 4px) | Không khai báo | 8px | button-label | Native box | Không override theo viewport | | default | Derived(36px = h-9 × 4px) | Derived(8px = py-2 × 4px) / Derived(16px = px-4 × 4px) | Không khai báo | 8px | button-label | Native box | Không override theo viewport | | lg | Derived(40px = h-10 × 4px) | 0 / Derived(32px = px-8 × 4px) | Không khai báo | 8px | button-label | Native box | Không override theo viewport | | icon | Derived(36px = h-9 × 4px) × Derived(36px = w-9 × 4px) | Theo utility | Không khai báo | 8px | button-label | Native box | iconOnly ép size icon | | auto | Theo parent (`h-full`) | Derived(8px = py-2 × 4px) / Derived(16px = px-4 × 4px) | Không khai báo | 8px | button-label | Theo parent | Caller quyết định height của parent | | Label desktop / mobile | Theo size | Theo size | Theo caller | Theo size | 12px / 16px → 15px / 22px; weight 500 | Không mở rộng hit area | JS mobile class khi mobileMaxWidth 899px | ### Tokens | Part | Token | Light | Dark | | --- | --- | --- | --- | | Primary fill | `--chatty-primary` | #6366f1 | #6366f1 | | Primary text | `--chatty-primary-foreground` | #ffffff | #ffffff | | Hover primary | `--chatty-primary-hover` | #4f46e5 | #4f46e5 | | Neutral fill | `--chatty-muted` | #f1f5f9 | #f1f5f9 | | Neutral text | `--chatty-muted-foreground` | #64748b | Merchant secondary when overridden by popup theme | | Destructive | `--chatty-destructive` | #ef4444 | #ef4444 | | Merchant action | `--faqsBtnPopupColor` / `--faqsFloatBtnLabelColor` | Màu merchant theo caller | fill #ffffff / text #303030, Dark override thắng biến merchant | | Focus | `--chatty-ring` | Merchant faqsTextColor, fallback #303030 | Merchant faqsTextColor, fallback #eee | | Neutral foreground | `--chatty-foreground` | #0f172a | Theo faqsTextColor của merchant | | Border | `--chatty-border` | #e2e8f0 | Same unless merchant overrides | | Shared radius | `--chatty-radius-md` | 8px; rounded-md maps to this token | Same | ### States | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Hover default | pointer | `hover:chatty:bg-primary-hover`; màu theo Tokens | Không thêm ARIA | | Hover outline | pointer | `hover:chatty:bg-muted`; màu theo Tokens | Không thêm ARIA | | Hover ghost | pointer | `hover:chatty:bg-muted`; màu theo Tokens | Không thêm ARIA | | Hover iconOnly | pointer | `hover:chatty:bg-muted`; màu theo Tokens | Không thêm ARIA | | Hover secondary | pointer | `hover:chatty:bg-muted/80`; màu theo Tokens | Không thêm ARIA | | Hover destructive | pointer | `hover:chatty:bg-destructive/90`; màu theo Tokens | Không thêm ARIA | | Pressed | pointer down / caller selected | No dedicated active fill; caller sets aria-pressed through `props` | Caller state | | Focus-visible | keyboard | 2px ring utility; popup outline 2px / offset 2px (`outline-offset`) | Native focus | | Disabled | disabled true | `opacity-50`, pointer-events-none | Native disabled only without href | | Primary-Button hover | pointer | opacity 0.8 (`opacity`), transition 0.2s ease-in | Caller label remains | | Primary-Button disabled | disabled | Light text #b5b5b5 / fill #00000014; Dark text #b5b5b5 / fill #ffffff14 | Native disabled | | Loading từ caller | loading \|\| !email | Label Send được thay bằng Spinner small; disabled không cho kích hoạt lặp. Không có prop loading nội tại. | Caller hiện tại không đặt aria-busy | ### Behaviour | Interaction | Result | | --- | --- | | Keyboard | Native `button` gets browser Enter/Space activation; anchor uses native link behavior. | | Overflow / long translation | inline-flex + fixed size utilities (`inline-flex`); no built-in line clamp; caller controls container and text. | | RTL / order | No custom RTL branch; caller composes icon and `children` in DOM order. | | Loading / errors | No built-in spinner/error variant; `props` forwarded, caller owns async lifecycle. | ### Copy | String | i18n key | Where | | --- | --- | --- | | Send | Send | EmailTranscript i18n caller (`Send`) | | Caller label | Caller-owned | Shared `children` does not localize strings. | ### Source | File | Evidence | | --- | --- | | | Shared API | | | Classic scope and caller class | | | Type role and breakpoint | ## AI Mode ### Import / element | Component / element | Import / file | Scope root | | --- | --- | --- | | `button` | | .chatty-ai-mode[data-theme] | | Native `button` caller | | .aimode-continue-ai under .chatty-ai-mode | ### Anatomy | Part | Element | | --- | --- | | 1 | Native `button` with chatty-btn + chosen variant. | | 2 | Loading holds text in `chatty-btn-label`, adds chatty-btn-spinner. | ### Placement / order | Context | Order | | --- | --- | | Continue with AI | Caller wraps one native action, disabled while `sending`. | ### Props | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | class | string | chatty-btn + accent / glass / ghost / danger classes | Caller | CSS kit has no React prop wrapper (`chatty-btn`). | | disabled | native boolean | true / false | false | Accent/glass visual branches (`disabled`). | | is-loading | CSS class | Caller toggle | absent | Caller also disables and supplies spinner (`is-loading`). | ### Sizes | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | base | min-height 32px | 0 12px | 6px | 10px via radius-sm | button-label | Native box; no extra hit-area | No size media query | | md | min-height 40px | 0 16px | 6px | 14px via radius-md | button-label | Native box | class-based | | lg | min-height 48px | 0 24px | 6px | 14px via radius-md | heading-large | Native box | class-based | | block | According to size | According to size | 6px | According to size | According to size | width 100% | class-based | | Label | Desktop / mobile | — | — | — | button-label Derived(14px = type(button-label, desktop, size)) / Derived(18px = type(button-label, desktop, line)) → Derived(17px = type(button-label, mobile, size)) / Derived(24px = type(button-label, mobile, line)), weight 500 | No extra hit-area | JS .is-mobile khi width ≤899px; hoặc media (hover: none) and (pointer: coarse), kể cả landscape >899px | | Large label | According to lg box | — | — | — | heading-large Derived(17px = type(heading-large, desktop, size)) / Derived(24px = type(heading-large, desktop, line)) desktop →Derived(19px = type(heading-large, mobile, size)) / Derived(26px = type(heading-large, mobile, line)) mobile; weight 600 (`heading-large`) | No extra hit-area | JS .is-mobile khi width ≤899px; hoặc media (hover: none) and (pointer: coarse), kể cả landscape >899px | ### Tokens | Part | Token | Light | Dark | | --- | --- | --- | --- | | Accent | `--accent` | Merchant --faqsBtnPopupColor, fallback #8b7be8 | Same definition | | On accent | `--on-accent` | Merchant label, fallback white | Same definition | | Hover accent | `--accent-deep` | 85% accent mixed with black | Same definition | | Glass fill | `--fill-2` | rgba(20,19,24,0.07) below 900px; rgba(255,255,255,0.65) at min-width 900px | rgba(255,255,255,0.1) | | Glass edge | `--glass-edge` | rgba(20,19,24,0.08) | rgba(255,255,255,0.12) | | Text | `--vib-1` | rgba(20,19,24,0.94) | rgba(255,255,255,0.96) | | Muted text | `--vib-3` | rgba(20,19,24,0.62) | rgba(255,255,255,0.62) | | Hover neutral | `--fill-hover` | rgba(20,19,24,0.1) below 900px; rgba(255,255,255,0.92) at min-width 900px | rgba(255,255,255,0.14) | | Danger | `--danger` | #ef4444 | #ef4444 | | Transition duration / easing | `--dur-2`; `--ease`; `out-emphasized` | Derived(200ms = duration(200)); cubic-bezier(0.2,0.8,0,1); transform uses 0.18s | Same | | Canvas | --bg-deep | #f6f4f0 | #131215 | ### States | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Hover | pointer | accent-deep / fill-hover; danger brightness 0.95 (`brightness(0.95)`) | Native | | Pressed | active not disabled | scale 0.965 (`scale(0.965)`) | No selected API | | Disabled | native disabled | accent uses fill-2/vib-3; glass fill-1/vib-3, transparent border (`--vib-3`) | Native disabled | | Focus-visible | keyboard | Không có rule focus riêng trong kit; browser vẽ outline mặc định. | Native | | Loading | is-loading + disabled | opacity 0.85, cursor progress; hidden label (`0.85`) | Caller aria-busy/name | | Spinner | loading child | 16×16px border 2px; 0.7s linear infinite (`0.7s`) | Caller aria-hidden | ### Behaviour | Interaction | Result | | --- | --- | | Long text | `nowrap`: no truncation or wrap; ensure available width or a controlled overflow region. | | Keyboard / RTL | Native button activation; no kit-specific RTL handler (`button`). | | Async | ContinueWithAI resets sending in finally; its `disabled` action has no spinner child. | | Transition timing | background / border-color / color / opacity use `--dur-2` and `--ease`; transform is 0.18s with same ease. Tokens alias --chatty-motion-duration-200 / --chatty-motion-ease-out-emphasized; inherited from consumer. | ### Copy | String | i18n key | Where | | --- | --- | --- | | Continue with AI | Continue with AI button | Caller uses `t` | ### Source | File | Evidence | | --- | --- | | | CSS kit geometry and states | | | Theme roots and palette | ## Admin ### Import / element | Component / element | Import / file | Scope root | | --- | --- | --- | | `Button` | @shopify/polaris | Global Polaris stylesheet + AppProvider context; caller .Avada-WidgetModeCard | ### Anatomy | Part | Element | | --- | --- | | 1 | Native semantics through `Button`, text/icon/spinner slots owned by Polaris. | | 2 | Caller may supply `SettingsIcon` for customize. | ### Placement / order | Context | Order | | --- | --- | | Widget mode | Customize action is sibling of select button (`Button`). | ### Props | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | variant | string | plain / primary / secondary / tertiary / monochromePlain | `secondary` | Runtime default. | | size | string | micro / slim / medium / large | `medium` | Runtime default. | | loading / disabled | boolean | true / false | false | `disabled \|\| loading` disables interaction. | | pressed | boolean | true / false | false | Selected CSS only when not disabled and no URL (`pressed`). | | tone / textAlign / fullWidth | string / boolean | critical / success; left,right,center,start,end | center / false | Layout/variant inputs (`textAlign`). | | icon / disclosure | IconSource / boolean | Optional icon; up/down/select | undefined | Library chooses icon and placeholder (`disclosure`). | | url / submit / accessibilityLabel | string / boolean | Navigation, submit, icon-only name | undefined / false | Caller-owned (`url`). | | children | ReactNode | Text/icon caller content | undefined | Passed through Text markup (`children`). | | id | string | Element id | undefined | Forwarded (`id`). | | external / download / target | boolean / boolean or string / string | Link attributes | undefined | Used with url (`external`, `download`, `target`). | | role / ariaControls / ariaExpanded / ariaDescribedBy / ariaChecked | string / string / boolean / string / boolean or mixed | Caller ARIA | undefined | Named API fields (`role`, `ariaControls`, `ariaExpanded`, `ariaDescribedBy`, `ariaChecked`). | | onClick / onFocus / onBlur / onKeyDown / onKeyPress / onKeyUp / onMouseEnter / onTouchStart / onPointerDown | function | Caller handlers | undefined | Named callbacks, not arbitrary rest props (`onClick`, `onPointerDown`). | | removeUnderline / dataPrimaryLink | boolean | Optional link rendering flags | undefined | Explicitly accepted (`removeUnderline`, `dataPrimaryLink`). | ### Sizes | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | micro | 24px / 28px | 4px / 8px | 2px | 8px | bodySm | Min box | CSS min-width:48em; px là giá trị token Polaris | | slim / medium | 28px / 32px | 6px / 12px | 2px | 8px | bodySm | Min box | CSS min-width:48em | | large | 32px / 36px | 6px / 12px | 2px | 8px | bodyMd | Min box | CSS min-width:48em | | Label bodySm | Theo size | Theo size | Theo size | Theo size | 12px / 16px | Native box | Mọi size trừ large và plain không phải micro | | Label bodyMd | Theo size | Theo size | Theo size | Theo size | 13px / 20px | Native box | large hoặc plain / monochromePlain không phải micro | | Weight medium | Root-relative | Theo size | Theo size | Theo size | medium 550 | Native box | light-mobile là theme class riêng; iOS Dynamic Type có thể đổi root | | Weight semibold (primary dưới mdUp) | Root-relative | Theo size | Theo size | Theo size | semibold 650 | Native box | light-mobile là theme class riêng; iOS Dynamic Type có thể đổi root | | Weight regular (plain) | Root-relative | Theo size | Theo size | Theo size | regular 450 | Native box | light-mobile là theme class riêng; iOS Dynamic Type có thể đổi root | | light-mobile bodySm | Theo size | Theo size | Theo size | Theo size | 14px / 20px | Native box | Theme class p-theme-light-mobile; không suy ra chỉ từ viewport | | light-mobile bodyMd | Theo size | Theo size | Theo size | Theo size | 16px / 24px | Native box | Theme class p-theme-light-mobile | ### Tokens | Part | Token | Light | Dark | | --- | --- | --- | --- | | Radius | --p-border-radius-200 | 8px | No Dark skin | | Internal spacing | --p-space-050 | 2px | No Dark skin | | Text | --p-color-text | rgba(48,48,48,1) | No Dark skin | | Surface | --p-color-bg-surface | rgba(255,255,255,1) | No Dark skin | | Focus | --p-color-border-focus | #005bd3 | No Dark skin | ### States | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Hover / active | pointer | Library swaps background / color / shadow (`--pc-button-bg_hover`). | Native | | Focus-visible | keyboard | 2px outline; 1px offset | Native | | Disabled | disabled or loading | No shadow, pointer-events none (`pointer-events:none`). | Native disabled / aria-disabled | | Pressed | pressed true | Selected background / text / shadow (`--pc-button-bg_pressed`). | aria-pressed | | Loading | loading true | Original label remains in layout, spinner small (`Spinner`). | aria-busy via UnstyledButton | ### Behaviour | Interaction | Result | | --- | --- | | Action / link | URL/submit forwarded to unstyled owner (`url`). | | Translation / wrap | Text via library `children`; no guide-specific clamp. | | Library version | Pinned dependency `13.9.5`; source guard validates owner pin. | ### Copy | String | i18n key | Where | | --- | --- | --- | | Customize | Caller literal | WidgetModeCard tooltip and accessibilityLabel (`Customize`). | | Loading | Polaris.Button.spinnerAccessibilityLabel | Library spinner i18n (`spinnerAccessibilityLabel`). | ### Source | File | Evidence | | --- | --- | | | Product owner/import/action | | | Pinned dependency API | | | Pinned dependency API | | | Pinned dependency layout | ## Admin · Knowledge files ### Import / element | Component / element | Import / file | Scope root | | --- | --- | --- | | `Button` | @avada/chatty-ui/components/button.js | .kb-ide-page > .kb-ide; inherited Polaris tokens | | Style owner | KnowledgeFiles.scss `button` | .kb-ide-page .kb-ide button:not(.Polaris-Button) | ### Anatomy | Part | Element | | --- | --- | | 1 | Tag native a/button chọn qua `href`. | | 2 | Nội dung `children`; caller thêm icon/spinner. | ### Placement / order | Context | Order | | --- | --- | | Shared component | Caller decides order; `children` rendered without grouping. | ### Props | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `variant` | string | default / outline / ghost / iconOnly / secondary / destructive | default | Fill và interaction utility. | | `size` | string | default / sm / lg / icon / auto | default | Không tự tăng box trên mobile. | | `disabled` | boolean | true / false | undefined | Native button nhận attribute; anchor không nhận disabled. | | `href` | string | URL | undefined | Truthy đổi Tag thành a. | | `iconOnly` | boolean | true / false | undefined | Ép variant iconOnly và size icon; inline background/border/outline none. | | `noBorder` | boolean | true / false | undefined | Inline border none. | | `className` | string | CSS classes | undefined | Gộp cuối utility list. | | `style` | object | CSS declarations | undefined | Merge cuối, có thể override inline icon/noBorder. | | `children` | ReactNode | Caller content | undefined | Không có copy hay i18n mặc định. | | `props` | attributes / handlers | Native attrs, onClick, aria-\* | Caller | Spread vào Tag; caller đặt type cho form. | ### Sizes | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | All native button sizes | 32px | 0 / 10px | Không khai báo | 8px | 13px / 20px; weight 450 | Native box | Page selector ghi đè utility; font:inherit thắng khai báo weight trong :where | | Anchor | Theo utility | Theo utility | Caller | Theo utility | Theo inherited type | Native link | Selector button không áp lên anchor | ### Tokens | Part | Token | Light | Dark | | --- | --- | --- | --- | | Fill | `--p-color-bg-surface` | white | No Dark skin | | Text | `--p-color-text` | #303030 | No Dark skin | | Border | `--p-color-border` | Polaris light token | No Dark skin | | Focus | `--p-color-border-focus` | #005bd3 | No Dark skin | ### States | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Hover | pointer | bg-surface-hover (`--p-color-bg-surface-hover`) | Native | | Disabled | disabled | opacity 0.48, not-allowed cursor (`0.48`) | Native disabled | | Focus-visible | keyboard | outline 2px, offset 2px (`outline-offset`) | Native | | Pressed | caller-selected | No additional selected fill; caller forwards `props`. | Caller aria-pressed | | Loading | caller async | Not available built-in; caller renders `children`. | Caller aria-busy | ### Behaviour | Interaction | Result | | --- | --- | | Surface boundary | Styles target non-Polaris `button`; anchors keep shared utility behavior. | | RTL / overflow | Không có rule RTL hay clamp riêng cho page button; caller quản lý text. | | No Dark skin | Page skin hiện dùng Light; preview không cung cấp Dark. | ### Copy | String | i18n key | Where | | --- | --- | --- | | Caller label | Caller-owned | `children` from shared component. | ### Source | File | Evidence | | --- | --- | | | Page scope, native button override | | | Shared prop surface | ## Do / Don't Do: chọn API theo surface và đọc kích thước trong bảng cùng surface. Don't: dùng prop loading của Polaris cho shared kit; state loading của shared kit do caller ghép. ## Accessibility Các tỷ lệ dưới đây đo ở foreground/background đã composite trong fixture merchant của preview. Merchant palette đổi thì đo lại; admin chỉ có Light. Disabled được loại khỏi phép đánh giá chữ đang hoạt động. | Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio | | --- | --- | --- | --- | --- | | Classic | Native button hoặc anchor, tên từ children | Button Enter/Space; anchor Enter; focus theo popup | Caller hiện tại không đặt live region trên action | Primitive Measured(#ffffff / #6366f1 = 4.47:1); destructive Measured(#ffffff / #ef4444 = 3.76:1); secondary Light Measured(#64748b / #f1f5f9 = 4.34:1); outline/ghost/iconOnly Light Measured(#0f172a / #ffffff = 17.85:1); action Dark override Measured(#303030 / #ffffff = 13.20:1) | | Classic loading | Spinner thay label | Nút disabled | Không aria-busy | Light: spinner `#ffffff` trên fill disabled `#00000014`: Measured(#ffffff / #00000014 over #ffffff = 1.19:1) | | AI Mode | Native button, tên do caller | Native activation; kit chưa có focus-visible riêng | Caller tự cung cấp busy status | danger Measured(#ffffff / #ef4444 = 3.76:1); glass --vib-1 trên composite --fill-2 + --bg-deep: Light desktop Measured(rgba(20,19,24,0.94) / rgba(255,255,255,0.65) over #f6f4f0 = 15.50:1), mobile Measured(rgba(20,19,24,0.94) / rgba(20,19,24,0.07) over #f6f4f0 = 12.85:1), Dark Measured(rgba(255,255,255,0.96) / rgba(255,255,255,0.1) over #131215 = 13.32:1); ghost Light Measured(rgba(20,19,24,0.62) / #f6f4f0 = 5.00:1), Dark Measured(rgba(255,255,255,0.62) / #131215 = 7.59:1) | | Admin | Native semantics từ Button / UnstyledButton | Loading / disabled không kích hoạt; focus theo bảng States | Spinner có localized accessible label | Primary Measured(#ffffff / #303030 = 13.20:1); secondary Measured(#303030 / #ffffff = 13.20:1); critical Measured(#ffffff / #c70a24 = 6.00:1); success text Measured(#014b40 / #ffffff = 10.09:1) | | Admin · Knowledge files | Shared children cung cấp tên | Native button; outline của page | Caller-owned | Các button variant trên Light Measured(#303030 / #ffffff = 13.20:1); anchor giữ shared style | ## Target ```target | Surface | Now | Target | Source | | --- | --- | --- | --- | | Classic | Box mặc định theo Sizes; chưa mở rộng hit area | Not in code yet — build with the body values. Mục tiêu action mobile có hit area 44px; đo palette của merchant trước khi đổi màu. | [WCAG — target size enhanced](https://www.w3.org/WAI/WCAG22/Understanding/target-size-enhanced.html) | | Classic | Prop loading nội tại Not available; caller hiện thay label bằng Spinner | Not available — new build follows Target. Thêm loading?: boolean, default false. Khi true: giữ nguyên width/height đã đo của label, để label visibility:hidden, đặt Spinner small 16px × 16px ở giữa bằng absolute positioning; disabled = disabled \|\| loading; aria-busy=true, giữ accessible name của label, chặn onClick lặp. Khi false trả lại label và trạng thái disabled của caller. | [WCAG — status messages](https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html) | | AI Mode | Kit không có focus-visible riêng; Chromium glass Dark đo outline:auto 1px rgb(153,200,255) | Not in code yet — build with the body values. Thêm :focus-visible outline 2px solid var(--vib-1), offset 2px, không đổi geometry. Đo contrast của ring trên từng nền. | | | Classic | Light loading: Spinner `#ffffff` trên fill disabled `#00000014` | Not in code yet — build with the body values. Spinner đổi sang màu đạt non-text contrast với fill disabled; đo lại trên nền merchant. | [WCAG — non text contrast](https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html) | | Classic / AI Mode | Tỷ lệ tương phản đo trong Accessibility | Not in code yet — build with the body values. Điều chỉnh các cặp đang thấp để chữ thường đạt 4.5:1, rồi đo lại từng theme. | [Contrast](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html) | | Classic · AI Mode · Admin | Component React theo surface | Not available — new build follows Target. Port `chatty-button`; Inbox Target: literal 2.0, phase 1b, 28px/full. Admin Catalogue: Inbox Target. Knowledge files: Polaris `Button`. | | ``` - [WCAG — target size enhanced](https://www.w3.org/WAI/WCAG22/Understanding/target-size-enhanced.html) - .kb-ide button - [WAI-ARIA APG — button](https://www.w3.org/WAI/ARIA/apg/patterns/button/) --- # Carousel dots Dấu vị trí trang trí dưới carousel. ## Key rules - Chấm thể hiện vị trí do caller tính và không phải nút điều khiển. - Element `chatty-carousel-dots` ở mục Standard là chuẩn chatty-ui port theo; các mục theo surface mô tả component React đang chạy. ## Use when / Avoid Dùng để bổ sung tín hiệu vị trí cho carousel. ### Use instead | Component | Use when | | --- | --- | | `CarouselDots` | Hiện vị trí carousel bằng dấu trang trí. | | `button` | Dùng nút khi cần điều khiển cuộn carousel. | ## Live preview Example (Standard) — Element chatty-carousel-dots: 5, 3 và 8 chấm; token chuẩn. ```html ``` Example (Standard) — Element chatty-carousel-dots trên AI Mode. ```html ``` Example (Current (React), being replaced) — Dấu vị trí với dữ liệu cục bộ. ```jsx import React from 'react'; import {CarouselDots} from '@scripttag/platform/components/CarouselDots/CarouselDots.jsx'; export function Catalogue() { return ; } ``` Example (Current (React), being replaced) — Dấu vị trí trong AI Mode. ```jsx import React from 'react'; import {CarouselDots} from '@scripttag/platform/components/CarouselDots/CarouselDots.jsx'; export function Catalogue() { return ; } ``` ## Standard Example (Standard) — Element chatty-carousel-dots: 5, 3 và 8 chấm; token chuẩn. ```html ``` Prototype (cùng `carousel-dots.styles.js` và ) là chuẩn: chatty-ui port 1:1 các file này, và `chatty-ui/custom-elements.json` sinh từ chính prototype. Chấm chỉ trang trí và ẩn với công nghệ hỗ trợ; carousel tự nêu vị trí và giữ control. Chưa surface nào dùng element thật; các mục bên dưới mô tả React đang chạy. ### Element | Element | Module | | --- | --- | | `chatty-carousel-dots` | @avada/chatty-ui/elements/carousel-dots.js | ### API | Kind | Name | Type | Default | Description | | --- | --- | --- | --- | --- | | attribute | `count` | number | `0` | Số chấm. | | attribute | `active` | number | `0` | Vị trí chấm đang active, tính từ 0. | | part | `base` | – | – | Hàng chấm. | | part | `dot` | – | – | Mỗi chấm; chấm active có thêm part active. | | part | `active` | – | – | Chấm đang active. | | css-property | `--chatty-carousel-dots-color` | – | – | Màu chấm; chấm thường trộn 24% màu này. | | css-property | `--chatty-carousel-dots-active-width` | – | – | Chiều rộng chấm active; mặc định space-500. Khoảng cách phía trên do caller đặt. | ## Classic ### Import / element | Component / element | Import / file | Scope root | | --- | --- | --- | | `CarouselDots` | @scripttag/platform/components/CarouselDots/CarouselDots.jsx | .Avada-Faqs_Popup | ### Anatomy | Part | Element | | --- | --- | | 1 | Wrapper chứa một span cho mỗi mục. | ### Placement / order | Context | Order | | --- | --- | | Carousel | Dấu nằm sau track trong caller. | ### Props | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `count` | number | Số mục | Caller | Quyết định số dấu. | | `active` | number | Chỉ số hiện tại | Caller | Chọn dấu có class is-active. | ### Sizes | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | Dot | 6px | Không có | 6px | 999px | Không có | Không tương tác | Rộng 6px; active rộng 18px | ### Tokens | Part | Token | Light | Dark | | --- | --- | --- | --- | | Ink | `--carousel-dots-ink` | Kế thừa khi thiếu token | Theo caller | ### States | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Active | Index bằng active | Rộng 18px và dùng currentColor. | Wrapper aria-hidden | | Reduced motion | prefers-reduced-motion reduce | Không transition. | Không đổi | ### Behaviour | Interaction | Result | | --- | --- | | Caller thay index | Đổi class của dấu active. | ### Copy | String | i18n key | Where | | --- | --- | --- | | Not available | Not available | Không có copy. | ### Source | File | Evidence | | --- | --- | | | API và markup | | | Style và motion | ## AI Mode ### Import / element | Component / element | Import / file | Scope root | | --- | --- | --- | | `CarouselDots` | @scripttag/platform/components/CarouselDots/CarouselDots.jsx | .chatty-ai-mode | ### Anatomy | Part | Element | | --- | --- | | 1 | Wrapper chứa một span cho mỗi mục. | ### Placement / order | Context | Order | | --- | --- | | Carousel | Dấu nằm sau track trong caller. | ### Props | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `count` | number | Số mục | Caller | Quyết định số dấu. | | `active` | number | Chỉ số hiện tại | Caller | Chọn dấu có class is-active. | ### Sizes | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | Dot | 6px | Không có | 6px | 999px | Không có | Không tương tác | Rộng 6px; active rộng 18px | ### Tokens | Part | Token | Light | Dark | | --- | --- | --- | --- | | Ink | `--carousel-dots-ink` | Kế thừa khi thiếu token | Theo caller | ### States | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Active | Index bằng active | Rộng 18px và dùng currentColor. | Wrapper aria-hidden | | Reduced motion | prefers-reduced-motion reduce | Không transition. | Không đổi | ### Behaviour | Interaction | Result | | --- | --- | | Caller thay index | Đổi class của dấu active. | ### Copy | String | i18n key | Where | | --- | --- | --- | | Not available | Not available | Không có copy. | ### Source | File | Evidence | | --- | --- | | | API và markup | | | Style và motion | ## Do / Don't Do: giữ caller đồng bộ index với vị trí cuộn. Don't: coi dấu trang trí là điều khiển tương tác. ## Accessibility | Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio | | --- | --- | --- | --- | --- | | Classic | Wrapper aria-hidden | Không focusable | Không có | Theo màu của caller | | AI Mode | Wrapper aria-hidden | Không focusable | Không có | Theo màu của caller | ## Target ```target | Surface | Now | Target | | --- | --- | --- | | Classic · AI Mode | Component React của kit chung | Not available — new build follows Target. Port `chatty-carousel-dots` từ mục Standard; carousel của khối sản phẩm ghép element này. | ``` - [WAI-ARIA APG — carousel](https://www.w3.org/WAI/ARIA/apg/patterns/carousel/) --- # Cart notice Thông báo kết quả giỏ hàng khi không có dòng giá hoặc số lượng hợp lệ. ## Key rules - Dùng kết quả từ caller; success có thể mở giỏ, failure hiển thị lý do. - Element `chatty-cart-notice` ở mục Standard là chuẩn chatty-ui port theo; các mục theo surface mô tả component React đang chạy. ## Use when / Avoid Dùng khi kết quả giỏ không đủ dữ liệu để dựng receipt chi tiết. ### Use instead | Component | Use when | | --- | --- | | `CartNotice` | Kết quả thêm giỏ thành công hoặc thất bại. | | `CartConfirmation` | Receipt có dòng giỏ chi tiết. | ## Live preview Example (Standard) — Một receipt cho năm dòng thêm cùng lượt; storefront hiện ba dòng và summary. ```html Canvas tote bagNatural / Large Ceramic mug Wool cap Linen scarf Leather wallet and 2 more products — view in cart View cart ``` Example (Standard) — Admin history dùng show-all để hiện hết năm dòng; không có action View cart. ```html Canvas tote bagNatural / Large Ceramic mug Wool cap Linen scarf Leather wallet and 2 more products — view in cart ``` Example (Standard) — Element chatty-cart-notice: đã thêm có View cart, và không thêm được có lý do. ```js import '@avada/chatty-ui/tokens/tokens.css'; import {IconAlertCircle, IconCheck} from '@avada/chatty-ui/elements/icon-glyphs.js'; // Standard: the chatty-cart-notice prototype chatty-ui ports from (chatty-ui/src/elements/cart-notice.js). import {html} from 'lit'; import '@avada/chatty-ui/elements/cart-notice.js'; import '@avada/chatty-ui/elements/button.js'; export function Standard() { return html` ${IconCheck({slot: 'icon'})} Cotton shirt View cart ${IconAlertCircle({slot: 'icon'})} Cotton shirt Sold out `; } ``` Example (Standard) — Element chatty-cart-notice: đã thêm có View cart, và không thêm được có lý do. ```js import '@avada/chatty-ui/tokens/tokens.css'; import {IconAlertCircle, IconCheck} from '@avada/chatty-ui/elements/icon-glyphs.js'; // Standard: the chatty-cart-notice prototype chatty-ui ports from (chatty-ui/src/elements/cart-notice.js). import {html} from 'lit'; import '@avada/chatty-ui/elements/cart-notice.js'; import '@avada/chatty-ui/elements/button.js'; export function Standard() { return html` ${IconCheck({slot: 'icon'})} Cotton shirt View cart ${IconAlertCircle({slot: 'icon'})} Cotton shirt Sold out `; } ``` Example (Standard) — Element chatty-cart-notice: đã thêm có View cart, và không thêm được có lý do. ```js import '@avada/chatty-ui/tokens/tokens.css'; import {IconAlertCircle, IconCheck} from '@avada/chatty-ui/elements/icon-glyphs.js'; // Standard: the chatty-cart-notice prototype chatty-ui ports from (chatty-ui/src/elements/cart-notice.js). import {html} from 'lit'; import '@avada/chatty-ui/elements/cart-notice.js'; import '@avada/chatty-ui/elements/button.js'; export function Standard() { return html` ${IconCheck({slot: 'icon'})} Cotton shirt View cart ${IconAlertCircle({slot: 'icon'})} Cotton shirt Sold out `; } ``` Example (Current (React), being replaced) — Kết quả thêm giỏ và lỗi với dữ liệu cục bộ. ```jsx import React from 'react'; import {CartNotice} from '@avada/chatty-ui/primitives/CartNotice.jsx'; export function Catalogue({surface}) { return
text} onViewCart={surface === 'admin' ? undefined : () => {}} /> text} />
; } ``` Example (Current (React), being replaced) — Kết quả trong widget Classic. ```jsx import React from 'react'; import {CartNotice} from '@avada/chatty-ui/primitives/CartNotice.jsx'; export function Catalogue({surface}) { return
text} onViewCart={surface === 'admin' ? undefined : () => {}} /> text} />
; } ``` Example (Current (React), being replaced) — Kết quả chỉ đọc trong inbox. ```jsx import React from 'react'; import {CartNotice} from '@avada/chatty-ui/primitives/CartNotice.jsx'; export function Catalogue({surface}) { return
text} onViewCart={surface === 'admin' ? undefined : () => {}} /> text} />
; } ``` ## Standard Grouped receipt: đặt `grouped` trên receipt cha, `heading` đã dịch, các receipt con trong slot `items`, summary đã dịch trong slot `more` và một action ở receipt cha. Trên storefront, hơn bốn dòng thì hiện ba dòng; `show-all` dành cho Admin history; Admin không có action View cart vì merchant không mở giỏ của shopper. API sinh ở [chatty-cart-confirmation](https://chatty-ui-research.avada-tesla-chatty.workers.dev/elements/chatty-cart-confirmation/). Example (Standard) — Element chatty-cart-notice: đã thêm có View cart, và không thêm được có lý do. ```js import '@avada/chatty-ui/tokens/tokens.css'; import {IconAlertCircle, IconCheck} from '@avada/chatty-ui/elements/icon-glyphs.js'; // Standard: the chatty-cart-notice prototype chatty-ui ports from (chatty-ui/src/elements/cart-notice.js). import {html} from 'lit'; import '@avada/chatty-ui/elements/cart-notice.js'; import '@avada/chatty-ui/elements/button.js'; export function Standard() { return html` ${IconCheck({slot: 'icon'})} Cotton shirt View cart ${IconAlertCircle({slot: 'icon'})} Cotton shirt Sold out `; } ``` Prototype (cùng `cart-notice.styles.js`) là chuẩn: chatty-ui port 1:1, và `chatty-ui/custom-elements.json` sinh từ chính prototype. Icon, tên sản phẩm, lý do và nút View cart đi vào qua slot; vùng thông báo đặt tên bằng tiêu đề cộng tên sản phẩm. Chưa surface nào dùng element thật; các mục bên dưới mô tả React đang chạy. ### Element | Element | Module | | --- | --- | | `chatty-cart-notice` | @avada/chatty-ui/elements/cart-notice.js | ### API | Kind | Name | Type | Default | Description | | --- | --- | --- | --- | --- | | attribute | `tone` | success, critical | `'success'` | success là đã thêm, critical là không thêm được; giá trị lạ quay về success. | | attribute | `heading` | string | `''` | Tiêu đề; rỗng thì dùng Added to cart hoặc Could not add to cart theo tone. | | slot | default | – | – | Tên sản phẩm. | | slot | `icon` | – | – | Icon trạng thái (check hoặc cảnh báo). | | slot | `detail` | – | – | Lý do lỗi, ví dụ Sold out. | | slot | `action` | – | – | Nút View cart; chỉ hiện khi tone success. | | part | `base` | – | – | Khung thông báo (section). | | part | `icon` | – | – | Vùng chứa icon. | | part | `label` | – | – | Dòng tiêu đề. | | css-property | `--chatty-cart-notice-radius` | – | – | Bo góc. | | css-property | `--chatty-cart-notice-background` | – | – | Nền. | ## AI Mode ### Import / element | Component / element | Import / file | Scope root | | --- | --- | --- | | `CartNotice` | @avada/chatty-ui/primitives/CartNotice.jsx | .chatty-ai-mode | ### Anatomy | Part | Element | | --- | --- | | 1 | Section chứa icon, nhãn và nội dung. | | 2 | Nút View cart tùy chọn ở kết quả thành công. | ### Placement / order | Context | Order | | --- | --- | | Notice | Icon trước body; nhãn, title, reason rồi action. | ### Props | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `notice` | object | Kết quả giỏ | Caller | Dữ liệu không hợp lệ trả null. | | `translate` | function | Hàm dịch | Caller | Dịch nhãn và action. | | `onViewCart` | function | Handler | undefined | Chỉ dùng ở kết quả thành công. | ### Sizes | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | Notice | Theo nội dung | 12px 16px | 10px | `radius.$card` | body-medium | Nút native | Rộng tối đa 360px | ### Tokens | Part | Token | Light | Dark | | --- | --- | --- | --- | | Text | `--chatty-color-text` | Fallback #303030 | Theo scope | | Failure | `--chatty-color-critical` | Fallback #c5280c | Theo scope | ### States | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Success | kind added | Icon check, có thể hiện View cart. | Native button | | Failure | kind failure | Icon alert, nhãn lỗi và reason nếu có. | Không thêm role | ### Behaviour | Interaction | Result | | --- | --- | | View cart | Gọi handler từ caller. | | Invalid notice | Trả null. | ### Copy | String | i18n key | Where | | --- | --- | --- | | Added to cart | Added to cart | Nhãn success | | Could not add to cart | Could not add to cart | Nhãn failure | | View cart | View cart | Action success | ### Source | File | Evidence | | --- | --- | | | API và markup | | | Style | ## Classic ### Import / element | Component / element | Import / file | Scope root | | --- | --- | --- | | `CartNotice` | @avada/chatty-ui/primitives/CartNotice.jsx | .Avada-Faqs_Popup | ### Anatomy | Part | Element | | --- | --- | | 1 | Section chứa icon, nhãn và nội dung. | | 2 | Nút View cart tùy chọn ở kết quả thành công. | ### Placement / order | Context | Order | | --- | --- | | Notice | Icon trước body; nhãn, title, reason rồi action. | ### Props | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `notice` | object | Kết quả giỏ | Caller | Dữ liệu không hợp lệ trả null. | | `translate` | function | Hàm dịch | Caller | Dịch nhãn và action. | | `onViewCart` | function | Handler | undefined | Chỉ dùng ở kết quả thành công. | ### Sizes | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | Notice | Theo nội dung | 12px 16px | 10px | `radius.$card` | body-medium | Nút native | Rộng tối đa 360px | ### Tokens | Part | Token | Light | Dark | | --- | --- | --- | --- | | Text | `--chatty-color-text` | Fallback #303030 | Theo scope | | Failure | `--chatty-color-critical` | Fallback #c5280c | Theo scope | ### States | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Success | kind added | Icon check, có thể hiện View cart. | Native button | | Failure | kind failure | Icon alert, nhãn lỗi và reason nếu có. | Không thêm role | ### Behaviour | Interaction | Result | | --- | --- | | View cart | Gọi handler từ caller. | | Invalid notice | Trả null. | ### Copy | String | i18n key | Where | | --- | --- | --- | | Added to cart | Added to cart | Nhãn success | | Could not add to cart | Could not add to cart | Nhãn failure | | View cart | View cart | Action success | ### Source | File | Evidence | | --- | --- | | | API và markup | | | Style | ## Admin ### Import / element | Component / element | Import / file | Scope root | | --- | --- | --- | | `CartNotice` | @avada/chatty-ui/primitives/CartNotice.jsx | .inbox-v2 | ### Anatomy | Part | Element | | --- | --- | | 1 | Section chứa icon, nhãn và nội dung. | | 2 | Nút View cart tùy chọn ở kết quả thành công. | ### Placement / order | Context | Order | | --- | --- | | Notice | Icon trước body; nhãn, title, reason rồi action. | ### Props | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `notice` | object | Kết quả giỏ | Caller | Dữ liệu không hợp lệ trả null. | | `translate` | function | Hàm dịch | Caller | Dịch nhãn và action. | | `onViewCart` | function | Handler | undefined | Chỉ dùng ở kết quả thành công. | ### Sizes | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | Notice | Theo nội dung | 12px 16px | 10px | `radius.$card` | body-medium | Nút native | Rộng tối đa 360px | ### Tokens | Part | Token | Light | Dark | | --- | --- | --- | --- | | Text | `--chatty-color-text` | Fallback #303030 | No Dark skin | | Failure | `--chatty-color-critical` | Fallback #c5280c | No Dark skin | ### States | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Success | kind added | Icon check, có thể hiện View cart. | Native button | | Failure | kind failure | Icon alert, nhãn lỗi và reason nếu có. | Không thêm role | ### Behaviour | Interaction | Result | | --- | --- | | View cart | Gọi handler từ caller. | | Invalid notice | Trả null. | ### Copy | String | i18n key | Where | | --- | --- | --- | | Added to cart | Added to cart | Nhãn success | | Could not add to cart | Could not add to cart | Nhãn failure | | View cart | View cart | Action success | ### Source | File | Evidence | | --- | --- | | | API và markup | | | Style | ## Do / Don't Do: dùng dữ liệu kết quả hợp lệ từ caller. Don't: hiển thị action mở giỏ trong thông báo lỗi. ## Accessibility | Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio | | --- | --- | --- | --- | --- | | AI Mode | Section và nút View cart native khi có action | Tab tới nút, Enter hoặc Space kích hoạt | Caller sở hữu thông báo | Theo scope của caller | | Classic | Section và nút View cart native khi có action | Tab tới nút, Enter hoặc Space kích hoạt | Caller sở hữu thông báo | Theo scope của caller | | Admin | Section và nút View cart native khi có action | Tab tới nút, Enter hoặc Space kích hoạt | Caller sở hữu thông báo | Theo scope của caller | ## Target ```target | Surface | Now | Target | Source | | --- | --- | --- | --- | | Classic · AI Mode · Admin | Component React | Not available — new build follows Target. Element (dự kiến): `chatty-cart-notice`; hiệu ứng giỏ hàng nằm ở module JS thuần, element chỉ hiển thị. | [MDN: Web Components](https://developer.mozilla.org/en-US/docs/Web/API/Web_components) | | AI Mode · Classic · Admin | Component React theo surface | Not available — new build follows Target. Port `chatty-cart-notice` từ mục Standard rồi chuyển caller từng surface. | | ``` - [MDN: Web Components](https://developer.mozilla.org/en-US/docs/Web/API/Web_components) --- # Suggestion chip Chip của kit chung; Knowledge files dùng nó làm chip lọc có nút xoá. ## Key rules - Dùng `Chip` với `size="small"`, `variant="outlined"` và `onDelete` cho bộ lọc đang bật. - CSS trang khai báo chip 11px, padding 2px 6px, nút xoá 16px × 16px. - Root `Chip` là `div` không tương tác; chỉ nút xoá là `button` có tên từ `deleteLabel`. - Element `chatty-chip` ở mục Standard là chuẩn chatty-ui port theo; các mục theo surface mô tả component React đang chạy. ## Use when / Avoid Dùng khi cần hiện một giá trị lọc đang chọn và cho gỡ từng giá trị. Chip không có prop selected, không có hành động trên thân chip và không có trạng thái disabled; gợi ý bước tiếp theo trong hội thoại không dùng component này trong source hiện tại. ### Use instead | Component | Use when | | --- | --- | | `Chip` | Hiện giá trị lọc đang bật kèm nút xoá, như Explorer. | | `Button` | Hành động có kết quả; thân `Chip` không nhận hành động. | ## Live preview Example (Standard) — Element chatty-chip: variant, size và nút xoá; token admin, không màu merchant. ```html Shipping Returns Selected Orders Website ``` Example (Standard) — Element chatty-chip size sm như thanh lọc Knowledge files: cao 20px, nút xoá 24px. ```html PDF Website Covered ``` Example (Current (React), being replaced) — Chip nhỏ, outlined và có nút xoá như Explorer; dữ liệu cục bộ. ```jsx import React, {useState} from 'react'; import {Chip} from '@avada/chatty-ui/components/chip.js'; const filters = [ {key: 'status', label: 'Status: Active'}, {key: 'verified', label: 'Verified'}, {key: 'topic', label: 'Topic: Shipping'} ]; export function Example() { const [active, setActive] = useState(filters); return (
{active.map(({key, label}) => ( setActive(current => current.filter(item => item.key !== key))} > {label} ))}
); } ``` ## Standard Example (Standard) — Element chatty-chip: variant, size và nút xoá; token admin, không màu merchant. ```html Shipping Returns Selected Orders Website ``` Prototype (cùng `chip.styles.js` và ) là chuẩn: chatty-ui port 1:1 các file này, và `chatty-ui/custom-elements.json` sinh từ chính prototype. Chưa surface nào dùng element thật; các mục theo surface bên dưới mô tả React đang chạy. Knowledge files vẫn chuyển sang Polaris theo Target; preview admin-kb chỉ để xem element dưới token admin. ### Element | Element | Module | | --- | --- | | `chatty-chip` | @avada/chatty-ui/elements/chip.js | ### API | Kind | Name | Type | Default | Description | | --- | --- | --- | --- | --- | | attribute | `variant` | secondary, tertiary | `'tertiary'` | tertiary viền (mặc định), secondary nền là trạng thái chọn. | | attribute | `size` | sm, md | `'md'` | Cỡ chữ và padding. | | attribute | `removable` | boolean | `false` | Thêm nút xoá ở cuối chip. | | attribute | `remove-label` | string | `'Remove'` | Tên truy cập của nút xoá. | | event | `chatty-remove` | `CustomEvent` | – | Nút xoá được kích hoạt; host tự gỡ chip. | | event | `click` | MouseEvent | – | Click native, retarget về host; nút xoá còn bắn chatty-remove. | | slot | default | – | – | Chữ của chip. | | slot | `remove-icon` | – | – | Thay glyph × mặc định của nút xoá. | | part | `base` | – | – | Khung pill. | | part | `label` | – | – | Vùng chứa chữ. | | part | `remove` | – | – | Nút xoá native. | | css-property | `--chatty-chip-background` | – | – | Nền theo variant. | | css-property | `--chatty-chip-color` | – | – | Màu chữ. | | css-property | `--chatty-chip-radius` | – | – | Bo góc; mặc định pill. | ## Admin · Knowledge files ### Import / element | Component / element | Import / file | Scope root | | --- | --- | --- | | `Chip` | @avada/chatty-ui/components/chip.js | .kb-ide-page .kb-ide\_\_active-filters | ### Anatomy | Part | Element | | --- | --- | | 1 | Root `div` của Chip, mang class kit và props. | | 2 | Nội dung `children` trong root. | | 3 | Nút xoá `button` chỉ có khi truyền `onDelete`; mặc định hiện ×. | ### Placement / order | Context | Order | | --- | --- | | Explorer filter | Một `Chip` cho mỗi bộ lọc đang bật, theo thứ tự activeFilters; cả khối chỉ render khi có ít nhất một bộ lọc. | ### Props | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `variant` | string | filled, outlined | `filled` | Explorer truyền `outlined`. | | `size` | string | small, medium | `medium` | Explorer truyền `small`. | | `color` | string | default, khác default | `default` | Chỉ đổi fill của `filled`; `outlined` bỏ qua. | | `onDelete` | function | Handler | undefined | Có giá trị thì render nút xoá. | | `deleteIcon` | ReactNode | Icon của caller | undefined | Thay ký tự ×. | | `deleteLabel` | string | Tên truy cập của nút xoá | `Remove` | Chuyển vào `aria-label`. | | `className` | string | CSS classes | undefined | Gộp cuối. | ### Sizes | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | kit small | Theo nội dung | `chatty:px-2` / `chatty:py-1` | `chatty:gap-1` | `chatty:rounded-full` | `chatty:text-xs` | Nút xoá `chatty:h-4` × `chatty:w-4` | Class theo `size` | | kit medium | Theo nội dung | `chatty:px-3` / `chatty:py-1` | `chatty:gap-1` | `chatty:rounded-full` | `chatty:text-sm` | Nút xoá `chatty:h-4` × `chatty:w-4` | Class theo `size` | | Knowledge files chip | Theo nội dung | 2px 6px | 4px giữa các chip | 8px | `font-size: 11px` | Không tương tác trên thân chip | Rule `.kb-ide__active-filters > div` | | Knowledge files remove | 16px × 16px | 0 | Không khai báo | Không khai báo | Theo chip | 16px × 16px | Rule `.kb-ide__active-filters button` | ### Tokens | Part | Token | Light | Dark | | --- | --- | --- | --- | | Chip text | `--p-color-text` | #303030 | No Dark skin | | Chip fill | `--p-color-bg-fill-secondary` | #f1f1f1 | No Dark skin | | Remove glyph | `--p-color-text-secondary` | #616161 | No Dark skin | | Focus ring | `--p-color-border-focus` | #005bd3 | No Dark skin | ### States | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Default | Render | Chip: fill và chữ theo Tokens, `border: 0`; nút xoá `border: 0` | Không thêm ARIA trên root | | Remove hover | pointer | Kit khai báo `hover:chatty:bg-black/10`; trang khai báo `--p-color-bg-surface-hover` cho button hover | Native | | Remove focus-visible | keyboard | outline 2px, offset 2px (`outline-offset`) | Native focus | | Remove disabled | Không có prop | Trang có rule cho button disabled nhưng Chip không truyền disabled xuống nút xoá | Not available | | Selected / pressed | Không có prop | Not available | Not available | ### Behaviour | Interaction | Result | | --- | --- | | Xoá | `onDelete` của Explorer đặt bộ lọc về false hoặc chuỗi rỗng. | | Nhiều chip | Container `flex-wrap: wrap`, khoảng cách 4px, margin-top 8px. | | Chữ dài | Không có clamp hay cắt dòng cho label; container chỉ wrap giữa các chip. | ### Copy | String | i18n key | Where | | --- | --- | --- | | Remove … filter | Remove ${filterLabels[key]} filter | `deleteLabel` của Explorer | | Remove | Remove | Mặc định của `deleteLabel` | | Nhãn bộ lọc | Caller-owned | Nội dung chip do Explorer ghép | ### Source | File | Evidence | | --- | --- | | | API và class kit | | | Caller duy nhất | | | Style chip trong Explorer | ## Do / Don't Do: đặt `deleteLabel` nêu rõ bộ lọc sẽ bị gỡ. Don't: gắn onClick vào thân `Chip`; root là `div`, không có keyboard. ## Accessibility | Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio | | --- | --- | --- | --- | --- | | Admin · Knowledge files | Root div không role; nút xoá là `button` có `aria-label` từ `deleteLabel` | Thân không focus; nút xoá Tab và Enter/Space native | Không có | Text Measured(#303030 / #f1f1f1 = 11.69:1); remove glyph Measured(#616161 / #f1f1f1 = 5.48:1) | ## Target ```target | Surface | Now | Target | Source | | --- | --- | --- | --- | | Admin · Knowledge files | Chip của kit chung làm chip lọc | Not available — new build follows Target. Knowledge files không dùng `chatty-*`: chuyển sang Polaris, vì trang admin ngoài inbox giữ Polaris. | [Shopify: Built for Shopify requirements](https://shopify.dev/docs/apps/launch/built-for-shopify/requirements) | | Classic · AI Mode · Admin | Component React theo surface | Not available — new build follows Target. Port `chatty-chip` từ mục Standard rồi chuyển caller từng surface; Inbox Target dùng token chatty-ui literal theo giá trị 2.0; gỡ wrapper hiện tại ở phase 1b trước khi chuyển caller. | | ``` - [Shopify: Built for Shopify requirements](https://shopify.dev/docs/apps/launch/built-for-shopify/requirements) --- # Composer / input Input một dòng của Classic: ba size, trạng thái error và disabled, tên truy cập do caller nối. ## Key rules - Classic: dùng `Input` với `size` small, medium hoặc large; chiều cao lấy từ `chatty:h-8`, `chatty:h-10`, `chatty:h-12`. - Classic: `Input` không render label và không render message lỗi; caller nối `htmlFor`/`id` và `aria-describedby`. - Classic: `error` chỉ đổi viền sang `chatty:border-destructive`; caller thêm `aria-invalid` và thông báo. - Classic: PopupBody vẽ focus-visible cho input bằng outline 2px; chữ input giữ role mobile 18px; tối đa 500px có sàn 16px. - `Input` là field một giá trị; vùng soạn tin nhiều dòng không dùng component này. ## Use when / Avoid Dùng cho dữ liệu một dòng như email hoặc tên. Không dùng placeholder làm label duy nhất. Vùng soạn tin và textarea là build riêng, không phải `Input`. ### Use instead | Component | Use when | | --- | --- | | `Input` | Field một dòng; Classic FormField dùng cho trường form. | | `textarea` | Field nhiều dòng; FormField dùng native textarea riêng. | ## Live preview Example — Input thật: large, error, read-only và disabled. ```jsx import React from 'react'; import {Input} from '@avada/chatty-ui/components/input.js'; export function Fields() { return (

Enter a valid email address.

); } ``` ## Classic ### Import / element | Component / element | Import / file | Scope root | | --- | --- | --- | | `Input` | @avada/chatty-ui | .chatty-widget > #Avada-FAQ_Widget > .Avada-Faqs_Popup | ### Anatomy | Part | Element | | --- | --- | | 1 | Native `input`; `type` mặc định là text. | | 2 | Label và message lỗi do caller đặt ngoài component. | ### Placement / order | Context | Order | | --- | --- | | Form chiến dịch | FormField render `Input` với `placeholder`; label không nằm trong `Input`. | ### Props | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `size` | string | small, medium, large | `medium` | Chọn height và padding ngang. | | `type` | string | HTML input type | `text` | Chuyển vào native input. | | `error` | boolean | true, false | `false` | Đổi viền sang destructive. | | `disabled` | boolean | true, false | `false` | Thêm `chatty:bg-muted` khi disabled. | | `className` | string | CSS classes | undefined | Gộp cuối danh sách class. | | `props` | attributes | Native attrs, handlers, ARIA | Caller | Spread vào input; caller đặt tên truy cập. | ### Sizes | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | small | Derived(32px = h-8 × 4px) | Derived(12px = px-3 × 4px) | Không khai báo | 8px (`chatty:rounded-md`) | input-value Derived(15px = type(input-value, desktop, size)) / Derived(22px = type(input-value, desktop, line)); weight 400 | Native box | Mobile role Derived(18px = type(input-value, mobile, size)) / Derived(24px = type(input-value, mobile, line)); tối đa 500px có sàn 16px, không giảm role | | medium | Derived(40px = h-10 × 4px) | Derived(12px = px-3 × 4px) | Không khai báo | 8px (`chatty:rounded-md`) | input-value Derived(15px = type(input-value, desktop, size)) / Derived(22px = type(input-value, desktop, line)); weight 400 | Native box | Mobile role Derived(18px = type(input-value, mobile, size)) / Derived(24px = type(input-value, mobile, line)); tối đa 500px có sàn 16px, không giảm role | | large | Derived(48px = h-12 × 4px) | Derived(16px = px-4 × 4px) | Không khai báo | 8px (`chatty:rounded-md`) | input-value Derived(15px = type(input-value, desktop, size)) / Derived(22px = type(input-value, desktop, line)); weight 400 | Native box | Mobile role Derived(18px = type(input-value, mobile, size)) / Derived(24px = type(input-value, mobile, line)); tối đa 500px có sàn 16px, không giảm role | ### Tokens | Part | Token | Light | Dark | | --- | --- | --- | --- | | Background | `--chatty-background` | #ffffff | Merchant `--faqsBgColor` | | Text | `--chatty-foreground` | #0f172a | Merchant `--faqsTextColor` | | Placeholder | `--chatty-muted-foreground` | #64748b | Merchant `--faqsTextColorSecondary` | | Border | `--chatty-border` | #e2e8f0 | #e2e8f0 | | Error border | `--chatty-destructive` | #ef4444 | #ef4444 | | Disabled fill | `--chatty-muted` | #f1f5f9 | #f1f5f9 | | Focus ring | `--chatty-ring` | Merchant `--faqsTextColor`, fallback #303030 | Merchant `--faqsTextColor`, fallback #eee | ### States | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Default | render | `chatty:border-border`, `chatty:bg-background` | Không thêm ARIA | | Hover | pointer | Nền giữ `--chatty-background`; Input không có viền hover riêng | Native | | Focus-visible | keyboard | outline 2px solid `--chatty-ring`, offset 2px | Native focus | | Error | `error` true | `chatty:border-destructive` | Caller đặt aria-invalid | | Disabled | `disabled` | `chatty:disabled:opacity-50`, `chatty:disabled:cursor-not-allowed`, `chatty:bg-muted` | Native disabled | | Read-only | readOnly attribute | Không có style riêng; giá trị vẫn đọc và chọn được | Native readonly | ### Behaviour | Interaction | Result | | --- | --- | | Keyboard | Native input nhận gõ và Tab; disabled bị loại khỏi Tab. | | Màn hình hẹp | Tối đa 500px: dùng max(16px, var(--chatty-type-input-value-size, 16px)) để giữ role và tránh iOS phóng to. | | Lỗi | `error` chỉ đổi viền; message và ARIA do caller cấp. | ### Copy | String | i18n key | Where | | --- | --- | --- | | Placeholder | Caller-owned | `placeholder` truyền từ FormField | | Label / lỗi | Caller-owned | Ngoài component | ### Source | File | Evidence | | --- | --- | | | API và element | | | Token và focus Classic | | | Caller | ## Do / Don't Do: nối label bằng `htmlFor` và `id`; lỗi nối bằng `aria-describedby`. Don't: chỉ đổi màu viền để báo lỗi. ## Accessibility | Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio | | --- | --- | --- | --- | --- | | Classic | `input` native; tên từ label của caller | Tab vào field; outline 2px offset 2px khi focus-visible | Caller-owned | Text Measured(#0f172a / #ffffff = 17.85:1); border Measured(#e2e8f0 / #ffffff = 1.23:1) | ## Target ```target | Surface | Now | Target | Source | | --- | --- | --- | --- | | Classic | Viền mặc định `--chatty-border` đo thấp hơn 3:1 trên nền trắng | Not in code yet — build with the body values. Viền field đạt 3:1 với nền thật; đo lại trên palette merchant. | [WCAG — non text contrast](https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html) | | Classic | `error` chỉ đổi màu viền | Not in code yet — build with the body values. Thêm message lỗi gắn aria-describedby và aria-invalid khi error true. | [WCAG — error identification](https://www.w3.org/WAI/WCAG22/Understanding/error-identification.html) | | Classic | Input React một dòng | Not available — new build follows Target. Element (dự kiến): `chatty-text-field`, form-associated (`setFormValue`, `setValidity`); nhãn qua attribute `label` hoặc slot `label`, slot `help`; part `control`; input đặt trong shadow, nếu autofill hỏng thì cho `` ở light DOM. | [MDN: ElementInternals](https://developer.mozilla.org/en-US/docs/Web/API/ElementInternals) | ``` - [WCAG — non text contrast](https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html) - [WCAG — error identification](https://www.w3.org/WAI/WCAG22/Understanding/error-identification.html) - [MDN: ElementInternals](https://developer.mozilla.org/en-US/docs/Web/API/ElementInternals) --- # Composer Draft tin nhắn có attachment, gửi bằng Enter và event tới host. ## Key rules - Element prototype là chuẩn để chatty-ui port theo. - Host giữ dữ liệu, dịch nhãn và xử lý event; preview chỉ dùng dữ liệu cục bộ. ## Use when / Avoid Dùng trong cuộc trò chuyện. Tránh nối trực tiếp element với API của shop. ### Use instead | Component | Use when | | --- | --- | | `Composer` | Implementation React đang chạy. | | Element prototype | Consumer chuyển sang custom element. | ## Live preview Example (Current (React), being replaced) — Component React thật; dữ liệu fixture, không gửi request. ```jsx import React, {useState} from 'react'; import ChatThread from '@scripttag/v2/views/ChatThread.jsx'; import {chatStore} from '@scripttag/v2/stores/chatStore.js'; import {WidgetTextRenderer} from '@assets/pages/InboxManagement/v2/blocks/WidgetTextRenderer.jsx'; import {Markdown} from '@avada/chatty-ui/primitives/Markdown.js'; import {MessageFrame} from '@avada/chatty-ui/canonical/MessageFrame.jsx'; import {CanonicalSurface} from '@avada/chatty-ui/canonical/Surface.jsx'; import {PreChatPrompt} from '@avada/chatty-ui/canonical/PreChatPrompt.jsx'; import {Composer} from '@avada/chatty-ui/primitives/Composer.js'; const message = { id: 'guide-reply', senderType: 'bot', text: 'The **canvas tote** is lightweight.', status: 'sent', createdAt: '2026-11-23T10:00:00Z', }; const store = {getState: () => ({messages: [message], loading: false}), subscribe: () => () => {}}; export function Compose() { return ( {}}> Send ` })} `; } ``` ### Current Example (Current (React), being replaced) — OfflineForm thật ở chế độ preview; không gửi dữ liệu ra ngoài. ```jsx import React from 'react'; import OfflineForm from '@scripttag/v1/Parts/OfflineForm/OfflineForm.jsx'; import {LiveDot} from '@scripttag/v2/components/LiveDot.jsx'; import {CHAT_STATUS, STATUS_DOT_COLOR} from '@assets/const/chatAvailability'; export function Offline({surface}) { if (surface === 'classic') return text} prepareBeforeSend={async () => true} isPreview />; return (
{[CHAT_STATUS.ONLINE, CHAT_STATUS.OFFLINE].map(state => ( {state} ))}
); } ``` Example (Current (React), being replaced) — LiveDot thật với màu STATUS_DOT_COLOR; markup bao quanh chỉ là fixture, không phải Panel header. ```jsx import React from 'react'; import OfflineForm from '@scripttag/v1/Parts/OfflineForm/OfflineForm.jsx'; import {LiveDot} from '@scripttag/v2/components/LiveDot.jsx'; import {CHAT_STATUS, STATUS_DOT_COLOR} from '@assets/const/chatAvailability'; export function Offline({surface}) { if (surface === 'classic') return text} prepareBeforeSend={async () => true} isPreview />; return (
{[CHAT_STATUS.ONLINE, CHAT_STATUS.OFFLINE].map(state => ( {state} ))}
); } ``` ## Classic ### Import / element #### OfflineForm | Component / element | Import / file | Scope root | | --- | --- | --- | | `OfflineForm` | import OfflineForm from '@scripttag/v1/Parts/OfflineForm/OfflineForm.jsx'; | .Avada-Faqs_Popup | ### Anatomy #### OfflineForm | Part | Element | | --- | --- | | 1 | Dòng dẫn đầu trước các field. | | 2 | Ba field có nhãn và dấu \* ngoài i18n: Name, Email address, Message. | | 3 | Dòng lỗi `p` với role alert khi gửi thất bại. | | 4 | Nút Send dùng class `Avada-Faqs_Primary-Button`. | ### Placement / order #### OfflineForm | Context | Order | | --- | --- | | Trong ChatPage | Form thay `ChatMessagesArea` khi `showOfflineForm` đúng; điều kiện nhường cho sign-in gate. | | Bên trong form | Dòng dẫn đầu, Name, Email address, Message, lỗi, Send. | ### Props #### OfflineForm | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `i18n` | Function | Hàm dịch của caller | None | Dịch mọi chuỗi trong form. | | `prepareBeforeSend` | Function | Hàm async của caller | None | Tạo hội thoại offline; trả về giá trị falsy thì form báo lỗi. | | `isPreview` | boolean | true / false | `false` | true: submit không làm gì. | ### Sizes #### OfflineForm | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | Form | Theo nội dung | 16px | 12px | Không khai báo | Kế thừa màu và cỡ chữ từ popup | Không áp dụng | Không có override theo viewport | | Label | Theo nội dung | Không khai báo | 4px | Không khai báo | body-medium Derived(15px = type(body-medium, desktop, size)) / Derived(22px = type(body-medium, desktop, line)) desktop → Derived(17px = type(body-medium, mobile, size)) / Derived(24px = type(body-medium, mobile, line)) mobile | Không tương tác | JS .mobile khi mobileMaxWidth 899px | | Input | 38px | 8px 12px | Không khai báo | Không khai báo | 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 | 38px | JS .mobile khi mobileMaxWidth 899px | | Send | min-height 44px | Theo style trình duyệt | Không khai báo | Không khai báo | 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 | ### Tokens #### OfflineForm | Part | Token | Light | Dark | | --- | --- | --- | --- | | Viền field | `--chatty-form-border` | #8a8a8a | #b0b0b0 | | Nền input | Không có token | Không khai báo | rgba(255, 255, 255, 0.16) | ### States #### OfflineForm | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Send disabled | Chưa hợp lệ hoặc đang gửi | opacity 0.5; trong popup Dark opacity 0.7 | Native disabled | | Đang gửi | Submit đang chạy | Field và Send disabled | `aria-busy` trên form | | Lỗi | prepareBeforeSend thất bại | Hiện dòng lỗi | role alert | | Preview | `isPreview` bật | Submit không làm gì | Không thêm ARIA | ### Behaviour #### OfflineForm | Interaction | Result | | --- | --- | | Gửi hợp lệ | Gọi prepareBeforeSend với nội dung, email, tên, type guest và cờ isOfflineForm. | | Validity | Send chỉ bật khi có tên, email hợp lệ và nội dung. | | Kích hoạt lặp | Bỏ qua submit khi preview, đang gửi hoặc chưa hợp lệ. | | Thất bại | Kết quả rỗng hoặc lỗi ném ra đều hiện dòng lỗi. | | Hiển thị | Form thay vùng tin nhắn khi showOfflineForm đúng; nhường cho sign-in gate. | ### Copy #### OfflineForm | String | i18n key | Where | | --- | --- | --- | | Leave your details and our team will get back to you. | Leave your details and our team will get back to you. | Dòng dẫn đầu | | Name | Name | Nhãn và placeholder; dấu \* nằm ngoài i18n | | Email address | Email address | Nhãn và placeholder | | Message | Message | Nhãn và placeholder | | Send | Send | Nút gửi | | Couldn't send. Please try again. | Couldn't send. Please try again. | Dòng lỗi | ### Source #### OfflineForm | File | Evidence | | --- | --- | | | API, validation và ARIA | | | Kích thước và state | | | Điều kiện hiển thị | ## AI Mode ### Import / element #### LiveDot | Component / element | Import / file | Scope root | | --- | --- | --- | | `LiveDot` | @scripttag/v2/components/LiveDot.jsx | .chatty-ai-mode; .aimode-panel-header-avatar | ### Anatomy #### LiveDot | Part | Element | | --- | --- | | 1 | Chấm trạng thái `chatty-live-dot`, màu lấy từ `dotColor`. | | 2 | Nhãn trạng thái trong `aimode-panel-header-status`, dưới tên shop. | ### Placement / order #### LiveDot | Context | Order | | --- | --- | | Panel header | Avatar kèm chấm ở góc; bên phải là tên shop rồi nhãn trạng thái; cả hai chỉ render khi có availability. | ### Props #### LiveDot | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `availability` | object hoặc null | label, state, dotColor | `null` | Panel nhận từ useChatAvailability; null thì ẩn chấm và nhãn. | | `useChatAvailability` | hook | Trả label, state, dotColor hoặc null | None | Null khi merchant chưa bật, thiếu cấu hình giờ hoặc không có label; tính lại mỗi phút. | ### Sizes #### LiveDot | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | Dot | 9px | Ring 2px | Không khai báo | 50% | Không có chữ | Không tương tác | Không có override theo viewport | | Label | Theo role | Không khai báo | Không khai báo | 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 #### LiveDot | Part | Token | Light | Dark | | --- | --- | --- | --- | | Chấm online | `STATUS_DOT_COLOR` | #29845A | Giống Light | | Chấm offline và holiday | `STATUS_DOT_COLOR` | #8C9196 | Giống Light | | Chấm break | `STATUS_DOT_COLOR` | #E6A700 | Giống Light | | Ring chấm | `--glass-edge` | rgba(20, 19, 24, 0.08) | rgba(255, 255, 255, 0.12) | | Chữ nhãn | `--vib-2` | rgba(20, 19, 24, 0.74) | rgba(255, 255, 255, 0.74) | ### States #### LiveDot | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Online | availability state online | Chấm nền #29845A | Không đặt attribute | | Offline hoặc holiday | availability state offline hoặc holiday | Chấm nền #8C9196 | Không đặt attribute | | Break | availability state break | Chấm nền #E6A700 | Không đặt attribute | | Ẩn | availability là null | Không render chấm và nhãn | Không có node | ### Behaviour #### LiveDot | Interaction | Result | | --- | --- | | Tính lại | Hook tính lại mỗi phút và khi presence của nhân viên đổi. | | Ẩn khi lỗi | Thiếu hoặc sai cấu hình giờ thì trả null, header không có trạng thái. | | Màu chấm | LiveDot đặt background từ dotColor; không có dotColor thì không đặt style. | ### Copy #### LiveDot | String | i18n key | Where | | --- | --- | --- | | Online status | Online status | Nhãn khi trong giờ và merchant chưa đổi nhãn | | Offline status message | Offline status message | Nhãn ngoài giờ khi merchant chưa đổi nhãn | | Usually reply in a few minutes | Usually reply in a few minutes | Nhãn offline mặc định theo cấu hình | ### Source #### LiveDot | File | Evidence | | --- | --- | | | Chấm trạng thái | | | Hook availability | | | CSS chấm và nhãn | ## Do / Don't Do: ẩn trạng thái khi chưa có cấu hình giờ thay vì hiện nhãn đoán. Don't: tự đặt nhãn hoặc màu trạng thái ngoài kết quả của hook. ## Accessibility | Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio | | --- | --- | --- | --- | --- | | Classic | Form có aria-busy khi gửi; label bọc từng field; lỗi nằm trong `p` với role alert. | Enter trong form gửi dữ liệu; Send disabled khi chưa hợp lệ. OfflineForm không quản lý focus sau khi gửi hay khi lỗi; không có control Retry riêng, người dùng bấm Send lại. | Lỗi trong role alert; không có live region cho thành công. | Không đo: màu chữ kế thừa từ popup và nền Send do class của merchant | | AI Mode | Chấm là span không có role hay tên; trạng thái đọc qua nhãn chữ. | Không tương tác và không nhận focus. | Không có live region; nhãn đổi khi hook tính lại. | Không đo vì nền glass có alpha | --- # Order lookup + verification Hỏi thông tin nhận diện đơn bằng một form rõ ràng ngay khi cần tra cứu. ## Key rules - Classic: form email nằm trong bubble của tin nhắn nhắc; nút Submit disabled tới khi email hợp lệ, sai email hiện `role="alert"`. - Classic: role `input-value` đọc 18px trên mobile để field không bị zoom. - AI Mode: dùng `ChatFormCard` với một `FormField` email; lỗi sai email hiện qua `chatty-field-error`. - Hỏi email theo số đơn của Smart link; không đòi nhập dữ liệu có cấu trúc trong văn xuôi. ## Use when / Avoid Dùng khi khách mở Smart link tới một đơn mà link không kèm email. Đây là xác thực đơn, không thay form thu thông tin pre-chat. ### Use instead | Component | Use when | | --- | --- | | `SmartLinkEmailForm` | Email để mở đơn của Smart link, ở Classic và AI Mode. | | `ChatFormCard` | Vỏ card chung cho form trong thread của AI Mode. | ## Entry points | Surface | Owner | | --- | --- | | Classic | SmartLinkOrderThread portal form vào bubble tin nhắn nhắc | | AI Mode | Block smartLinkEmailForm trong ChatMessage | ## Flow | Surface | Step | Trigger | UI shown | Component | Copy + i18n key | Timing | | --- | --- | --- | --- | --- | --- | --- | | Classic | Nhắc nhập email | Link không kèm email | Tin nhắn nhắc nhập email kèm số đơn | SmartLinkOrderThread | Please enter the email used for order #{{order_number}} so we can show its details. / cùng chuỗi | Ngay khi mở thread | | Classic | Gửi email | Submit | Nút aria-disabled khi chờ; field readonly giữ focus | SmartLinkEmailForm | Submit / Submit | Theo `onSubmit` | | Classic | Sai email | `onSubmit` không tìm thấy đơn | Lỗi `role="alert"` dưới input | SmartLinkEmailForm | That email doesn't match order #{{order_number}}. Check the email you used when you ordered and try again. / cùng chuỗi | Ngay sau response | | AI Mode | Hiện form | Block smartLinkEmailForm | Card form một field email | SmartLinkEmailForm | Email input placeholder / Email input placeholder | Ngay khi block render | | AI Mode | Gửi email | Nút hoặc Enter | `is-loading`, field và nút disabled | SmartLinkEmailForm | Submit / Submit | Theo `confirmOrderEmail` | | AI Mode | Sai email | Store báo `isWrongEmail` | Lỗi dưới field, viền `--danger` | SmartLinkEmailForm | Smart link order email mismatch / Smart link order email mismatch | Ngay sau response | ## Edge cases | Surface | Case | Behaviour | | --- | --- | --- | | Classic | Link sai hoặc không tìm thấy đơn | Hiện thông báo không tìm thấy, không có form | | Classic | Không có số đơn | Lời nhắc và lỗi dùng chuỗi không có số đơn | | AI Mode | Email chưa đủ hợp lệ | Nút disabled, Enter không gửi | | AI Mode | Đã xác minh | Post-purchase kết hợp phần đơn hàng và rewards. | ## 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) — 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`A${content.sender ?? message.senderName ?? message.senderMeta?.name ?? 'Assistant'}` }; }; return html`
${ mobileSheet ? html`

Example storefront

{ event.currentTarget.textContent = 'Products opened'; }} > Browse products
${surface === 'ai-mode' ? html`` : ''}` : '' }
${headerStart ?? ''} ${surface === 'admin' ? '' : html`S`} ${title ?? (surface === 'admin' ? 'Customer conversation' : strings.header)}${surface === 'admin' ? html`Customer` : status == null ? '' : html`${status === 'online' ? 'Open' : 'Closed'}`} ${headerActions ?? ''} ${ surface === 'admin' ? '' : html` toggle(event, true)} >${IconClose()}` }
${content ?? ''} { 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 } ]); }} >
${ surface === 'admin' ? '' : surface === 'ai-mode' ? html`` : html`` }
`; } import {createBlockRegistry} from '@avada/chatty-ui/behaviors/block-registry.js'; import '@avada/chatty-ui/elements/chatty-block-email-verify.js'; export function Standard({surface}) { const registry = createBlockRegistry({ 'email-verify': {tag: 'chatty-block-email-verify', wide: true} }); const store = fixtureStore([ question, { id: 'verify', senderType: 'bot', text: 'Please enter the email used for order #1001 so we can show its details.', blocks: [{type: 'email-verify', data: {number: '1001'}}] } ]); const update = data => store.setMessages( store .getState() .messages.map(m => m.id === 'verify' ? {...m, blocks: [{type: 'email-verify', data: {number: '1001', ...data}}]} : m ) ); return html`
{ update({loading: true}); const finish = () => update({mismatch: true}); if (matchMedia('(prefers-reduced-motion: reduce)').matches) finish(); else setTimeout(finish, 450); }} > ${patternShell({surface, store, registry})}
`; } ``` Email verify nằm trong tin bot; fixture luôn trả mismatch để kiểm sửa email và retry. Unlock order/rewards thật: N/A trong preview. ### Current Example (Current (React), being replaced) — SmartLinkEmailForm thật của AI Mode, trạng thái ban đầu từ smartLinkOrderStore. ```jsx import React, {useState} from 'react'; import SmartLinkEmailForm from '@scripttag/v1/Parts/SmartLinkOrder/SmartLinkEmailForm'; import {SmartLinkEmailForm as AiSmartLinkEmailForm} from '@scripttag/v2/components/ChatBlocks/SmartLinkEmailForm.jsx'; import {smartLinkOrderStore} from '@scripttag/v2/stores/smartLinkOrderStore.js'; export function AiEmail() { const [ready] = useState(() => seed(false)); return ready ? : null; } ``` Example (Current (React), being replaced) — Cùng form với `isWrongEmail` bật trong store thật: lỗi email không khớp số đơn. ```jsx import React, {useState} from 'react'; import SmartLinkEmailForm from '@scripttag/v1/Parts/SmartLinkOrder/SmartLinkEmailForm'; import {SmartLinkEmailForm as AiSmartLinkEmailForm} from '@scripttag/v2/components/ChatBlocks/SmartLinkEmailForm.jsx'; import {smartLinkOrderStore} from '@scripttag/v2/stores/smartLinkOrderStore.js'; export function AiEmailMismatch() { const [ready] = useState(() => seed(true)); return ready ? : null; } ``` Example (Current (React), being replaced) — Form email thật của Classic; onSubmit cục bộ luôn báo sai email để thấy trạng thái lỗi. ```jsx import React, {useState} from 'react'; import SmartLinkEmailForm from '@scripttag/v1/Parts/SmartLinkOrder/SmartLinkEmailForm'; import {SmartLinkEmailForm as AiSmartLinkEmailForm} from '@scripttag/v2/components/ChatBlocks/SmartLinkEmailForm.jsx'; import {smartLinkOrderStore} from '@scripttag/v2/stores/smartLinkOrderStore.js'; export function Email() { return ( text.replace(/{{(\w+)}}/g, (_, key) => values[key])} onSubmit={async () => false} /> ); } // The store holds the verdict of the last email check; the story freezes it. const seed = isWrongEmail => { smartLinkOrderStore.setState({status: 'form', number: '1001', isWrongEmail}); return true; }; ``` ## Classic ### Import / element #### SmartLinkEmailForm | Component / element | Import / file | Scope root | | --- | --- | --- | | `SmartLinkEmailForm` | import SmartLinkEmailForm from '@scripttag/v1/Parts/SmartLinkOrder/SmartLinkEmailForm'; | .Avada-Faqs_Popup | ### Anatomy #### SmartLinkEmailForm | Part | Element | | --- | --- | | 1 | Form `Avada-Faqs_SmartLink-Form`. | | 2 | Input email với `aria-label`. | | 3 | Lỗi sai email `role="alert"`, chỉ hiện sau khi submit thất bại. | | 4 | Nút `submit`. | ### Placement / order #### SmartLinkEmailForm | Context | Order | | --- | --- | | Tin nhắn nhắc nhập email | Form được portal vào bubble của tin nhắn nhắc; thứ tự: lời nhắc, input, lỗi (nếu có), nút Submit. | ### Props #### SmartLinkEmailForm | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `number` | string | Số đơn mà email phải khớp | Không có | Hiện trong lời nhắc và lỗi | | `placeholder` | string | Chuỗi i18n Email input placeholder | Không có | Truyền từ hook | | `label` | function | Hàm dịch có English fallback | Không có | Dùng cho aria-label và nút | | `onSubmit` | function | Nhận email đã trim; trả true khi tìm thấy đơn | Không có | Sai thì form hiện lỗi | ### Sizes #### SmartLinkEmailForm | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | input | Theo padding và role | `--chatty-space-250` / `--chatty-space-300` | `--chatty-space-200` bên dưới | 8px | `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 | Width 100% | Mobile theo class `.mobile` | | button | Theo padding và role | `--chatty-space-250` / `--chatty-space-300` | — | 8px | `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 | Width 100% | Mobile theo class `.mobile` | | error | Theo role | — | `--chatty-space-200` bên dưới | — | `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 phải điều khiển | Mobile theo class `.mobile` | ### Tokens #### SmartLinkEmailForm | Part | Token | Light | Dark | | --- | --- | --- | --- | | Viền input | `--chatty-color-border` | #e3e3e3 | #ffffff17 | | Nền input | `--chatty-color-bg-surface` | #fff | #1a1a1a | | Chữ input | `--chatty-color-text` | #303030 | #eee | | Nền nút | `--chatty-color-accent` | #303030 | #eee | | Chữ nút | `--chatty-color-on-accent` | #fff | #1a1a1a | | Nút disabled | `--chatty-color-text-disabled` | #767676 | #999 | | Chữ lỗi | `--chatty-color-critical` | #c5280c | #ff9a8a | ### States #### SmartLinkEmailForm | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Email chưa hợp lệ | Chuỗi không khớp regex | Nút disabled, nền `--chatty-color-text-disabled`, con trỏ mặc định. | `disabled` | | Đang gửi | `loading` true | Nút disabled; form chờ `onSubmit`. | `disabled` | | Sai email | `onSubmit` không tìm thấy đơn | Hiện lỗi; nút bật lại khi `loading` false. | `role="alert"` | | Focus-visible | keyboard | Outline 2px `var(--chatty-ring)`, offset 2px. | Native focus | ### Behaviour #### SmartLinkEmailForm | Interaction | Result | | --- | --- | | Submit | `preventDefault`, gọi `onSubmit` với email đã trim. | | Tìm thấy đơn | Phụ huynh thay form bằng thông tin đơn; form không tự cập nhật. | | Enter | Form native nên Enter trong input gửi form. | ### Copy #### SmartLinkEmailForm | String | i18n key | Where | | --- | --- | --- | | Please enter the email used for order #{{order_number}} so we can show its details. | Please enter the email used for order #{{order_number}} so we can show its details. | Lời nhắc trong bubble | | Email | Email | `aria-label` của input | | Submit | Submit | Nút gửi | | That email doesn't match order #{{order_number}}. Check the email you used when you ordered and try again. | That email doesn't match order #{{order_number}}. Check the email you used when you ordered and try again. | Lỗi sai email | ### Source #### SmartLinkEmailForm | File | Evidence | | --- | --- | | | Form | | | Style form | | | Portal vào bubble | | | Điều kiện hiện form | ## AI Mode ### Import / element #### SmartLinkEmailForm | Component / element | Import / file | Scope root | | --- | --- | --- | | `SmartLinkEmailForm` | @scripttag/v2/components/ChatBlocks/SmartLinkEmailForm.jsx | .chatty-ai-mode[data-theme] | ### Anatomy #### SmartLinkEmailForm | Part | Element | | --- | --- | | 1 | `ChatFormCard` bao form. | | 2 | `FormFields` với một `FormField` email, `wide`. | | 3 | Lỗi `chatty-field-error` với `role="alert"` do FormField vẽ khi có `error`. | | 4 | `FormActions` với nút accent `smart-link-email-submit`. | ### Placement / order #### SmartLinkEmailForm | Context | Order | | --- | --- | | Block `smartLinkEmailForm` trong thread | Card rộng hết lane; thứ tự: field email, nút Submit. | ### Props #### SmartLinkEmailForm | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `number` | string | Số đơn mà email phải khớp | Không có | Chuyển vào `confirmOrderEmail` và thông báo lỗi | ### Sizes #### SmartLinkEmailForm | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | card | Theo nội dung | 18px | 14px | `--radius-card` (20px) | Role theo field và nút | Card không phải điều khiển | Max-width 380px khi chỉ có một field; mobile `.is-mobile` đổi padding 15px, khoảng cách 12px | | input | Theo padding và role | 11px / 13px | 5px giữa label và lỗi | `--radius-sm` (10px) | `body-large`: Derived(17px = type(body-large, desktop, size)) / Derived(24px = type(body-large, desktop, line)) desktop, Derived(19px = type(body-large, mobile, size)) / Derived(26px = type(body-large, mobile, line)) mobile | Width 100% | Role đổi theo `.is-mobile` | | button | min-height 40px | 0 / 16px | — | `--radius-md` (14px) | `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 | Min-height 40px | `.is-mobile` đặt nút width 100% | ### Tokens #### SmartLinkEmailForm | Part | Token | Light | Dark | | --- | --- | --- | --- | | Viền input | `--glass-edge` | rgba(20, 19, 24, 0.08) | rgba(255, 255, 255, 0.12) | | Chữ input | `--vib-1` | rgba(20, 19, 24, 0.94) | rgba(255, 255, 255, 0.96) | | Nút disabled | `--vib-3` | rgba(20, 19, 24, 0.62) | rgba(255, 255, 255, 0.62) | | Lỗi | `--danger` | #ef4444 | #ef4444 | ### States #### SmartLinkEmailForm | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Email chưa hợp lệ | `isEmail(email)` false | Nút disabled, nền `--vib-3`. | `disabled` | | Đang gửi | `submitting` true | Class `is-loading`; nút disabled; field disabled. | `disabled` | | Sai email | `isWrongEmail` true | Input `is-error` viền `--danger`; lỗi hiện dưới field. | `aria-invalid`; `role="alert"` | | Focus input | keyboard | Viền `--accent`; halo `0 0 3px` qua `--focus-ring`. | Native focus | ### Behaviour #### SmartLinkEmailForm | Interaction | Result | | --- | --- | | Submit | Nút hoặc Enter trong field gọi `confirmOrderEmail({number, email})`. | | Kết thúc | `submitting` về false trong `finally`. | ### Copy #### SmartLinkEmailForm | String | i18n key | Where | | --- | --- | --- | | Email input placeholder | Email input placeholder | Placeholder của field | | Smart link order email mismatch | Smart link order email mismatch | Lỗi sai email, nhận `number` | | Submit | Submit | Nút gửi | ### Source #### SmartLinkEmailForm | File | Evidence | | --- | --- | | | Form | | | Card form dùng chung | | | Field và lỗi | ## Do / Don't Do: nêu rõ email cần nhập là email đã dùng khi đặt đơn. Don't: coi form pre-chat là bằng chứng đã xác thực đơn. ## Accessibility | Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio | | --- | --- | --- | --- | --- | | Classic | Input có `aria-label`; nút `submit` | Form native; Enter gửi; focus ring theo States | `role="alert"` cho lỗi sai email | Nút: Light Measured(#ffffff / #303030 = 13.20:1); Dark Measured(#1a1a1a / #eeeeee = 15.00:1). Lỗi: Light Measured(#c5280c / #ffffff = 5.70:1); Dark Measured(#ff9a8a / #1a1a1a = 8.49:1) | | AI Mode | Field có `aria-invalid` khi lỗi; nút `button` | Enter trong field gửi; focus input theo States | `role="alert"` cho lỗi sai email | Không đo ở trang này: nền field lấy từ token fill của AI Mode | ## Target ```target | Surface | Now | Target | | --- | --- | --- | | Classic | Input dùng `--chatty-form-border` ở các form khác nhưng form này dùng `--chatty-color-border` | Not in code yet — build with the body values. Target: đổi viền input sang `--chatty-form-border` để khớp mọi field khác của Classic. | ``` --- # Product recommendation Trả lời nhu cầu trước rồi đưa một nhóm sản phẩm có lý do phù hợp. ## Key rules - Classic: card rộng 205px và cuộn ngang; `SlideButton` chỉ hiện khi còn chỗ cuộn. - AI Mode: card chat rộng 184px; chỉ render sản phẩm được reply nhắc tới (`getMentionedProducts`). - Admin: dùng lại carousel Classic với `isAdmin`; nút thêm giỏ bị khoá. - Chọn card mở chi tiết trong chat khi có thể; trường hợp merchant ẩn chi tiết hoặc cần báo giá mở trang store. ## Use when / Avoid Dùng khi reply nhắc tới sản phẩm cụ thể. Danh mục chung hoặc kết quả tìm kiếm dài dùng trang kết quả riêng. ### Use instead | Component | Use when | | --- | --- | | `ChatbotProductsMessage` | Carousel sản phẩm của Classic và inbox. | | `ChatProductCarousel` | Carousel sản phẩm của AI Mode. | | `ProductCard` | Card sản phẩm của AI Mode; Classic có card riêng trong ChatbotProductsMessage. | ## Entry points | Surface | Owner | | --- | --- | | Classic | Reply có chatbotProducts, render bởi ChatbotProductsMessage | | AI Mode | Block products trong ChatMessage | | Admin | Block ChatbotProductsBlock trong inbox | ## Flow | Surface | Step | Trigger | UI shown | Component | Copy + i18n key | Timing | | --- | --- | --- | --- | --- | --- | --- | | Classic | Hiện carousel | Reply có sản phẩm | Row cuộn ngang các card | ChatbotProductsMessage | Không có chuỗi riêng | Cuộn smooth | | Classic | Chọn ảnh | Click nút media | Chi tiết trong chat, hoặc tab mới khi bị ẩn hoặc cần báo giá | ProductCard | View product details / View product details | Ngay khi click | | Classic | View similar | Click nút overlay | Gửi tin nhắn tìm sản phẩm tương tự | ProductCard | View similar / View similar | Ngay khi click | | AI Mode | Hiện carousel | Reply nhắc tới sản phẩm | Carousel card 184px | ChatProductCarousel | Không có chuỗi riêng | Không có timeout trong component | | AI Mode | Chọn card | Click hoặc Enter/Space | Chi tiết trong panel, hoặc trang store khi không có handle | ProductCard | View product / View product | Ngay khi chọn | | AI Mode | Thêm giỏ | Bấm nút thêm giỏ | Thêm thẳng hoặc mở chi tiết | AddToCartButton | Add to cart / Add to cart | Theo request của caller | | Admin | Hiện carousel | Block có sản phẩm | Carousel Classic, nút thêm giỏ khoá | ChatbotProductsBlock | Không có chuỗi riêng | Không có timeout trong block | ## Edge cases | Surface | Case | Behaviour | | --- | --- | --- | | Classic | Hết hàng | Nút thêm giỏ disabled và có tooltip Out of stock | | Classic | Cần báo giá | Không có khối thêm giỏ; ảnh mở link trang store | | AI Mode | Không có sản phẩm được nhắc | Không render carousel | | AI Mode | Launcher bị ẩn | Card mở trang store cùng tab | | Admin | Block không có sản phẩm | Trả null | ## 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`A${content.sender ?? message.senderName ?? message.senderMeta?.name ?? 'Assistant'}` }; }; return html`
${ mobileSheet ? html`

Example storefront

{ event.currentTarget.textContent = 'Products opened'; }} > Browse products
${surface === 'ai-mode' ? html`` : ''}` : '' }
${headerStart ?? ''} ${surface === 'admin' ? '' : html`S`} ${title ?? (surface === 'admin' ? 'Customer conversation' : strings.header)}${surface === 'admin' ? html`Customer` : status == null ? '' : html`${status === 'online' ? 'Open' : 'Closed'}`} ${headerActions ?? ''} ${ surface === 'admin' ? '' : html` toggle(event, true)} >${IconClose()}` }
${content ?? ''} { 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 } ]); }} >
${ surface === 'admin' ? '' : surface === 'ai-mode' ? html`` : html`` }
`; } import '@avada/chatty-ui/elements/chatty-block-products.js'; const products = [ { id: 'tote', title: 'Canvas tote', amount: 24, price: '$24.00', compareAtPrice: '$32.00', image: 'https://chatty-ui-research.avada-tesla-chatty.workers.dev/fixtures/tote.svg' }, { id: 'cap', title: 'Cotton cap', amount: 18, price: '$18.00', image: 'https://chatty-ui-research.avada-tesla-chatty.workers.dev/fixtures/cap.svg', available: false }, { id: 'mug', title: 'Stoneware mug', amount: 16, price: '$16.00', image: 'https://chatty-ui-research.avada-tesla-chatty.workers.dev/fixtures/mug.svg', cartState: 'error', cartError: 'Could not add to cart' } ]; /** Builds a shopping thread with isolated host-owned fixture cart state. * @param {string} surface * @returns {Object} */ function cartPattern(surface) { const store = fixtureStore([ question, { id: 'products', senderType: 'bot', text: 'Here are three options for you.', blocks: [{type: 'products', data: {products}}] } ]); const add = event => { const product = event.detail.product; const update = cartState => store.setMessages( store.getState().messages.map(m => m.id !== 'products' ? m : { ...m, blocks: [ { type: 'products', data: { products: m.blocks[0].data.products.map(p => p.id === product.id ? {...p, cartState} : p ) } } ] } ) ); update('loading'); const finish = () => { update('added'); if (surface === 'ai-mode') store.setMessages([ ...store.getState().messages, { id: `receipt-${store.getState().messages.length}`, senderType: 'bot', blocks: [ { type: 'cart-confirmation', data: { receipts: [ {title: product.title, quantity: 1, linePrice: product.amount, currency: 'USD'} ] } } ] } ]); setTimeout(() => update('idle'), surface === 'classic' ? 2000 : 1650); }; if (matchMedia('(prefers-reduced-motion: reduce)').matches) finish(); else setTimeout(finish, 450); }; if (surface === 'admin') store.setMessages([ ...store.getState().messages, { id: 'receipt', senderType: 'bot', blocks: [ { type: 'cart-confirmation', data: {receipts: [{title: 'Canvas tote', quantity: 1, linePrice: 24, currency: 'USD'}]} } ] } ]); return html`
{ const line = store .getState() .messages.flatMap(message => message.blocks ?? []) .filter(block => block.type === 'cart-confirmation') .at(-1).data.receipts[0]; store.setMessages([ ...store.getState().messages, { id: `bag-${store.getState().messages.length}`, senderType: 'bot', text: `Your bag: ${line.title} × ${line.quantity} — ${new Intl.NumberFormat('en', {style: 'currency', currency: line.currency}).format(line.linePrice)}` } ]); }} > ${patternShell({surface, store})}
`; } export function Standard({surface}) { return cartPattern(surface); } ``` Example (Standard) — Admin read-only Standard. ```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`A${content.sender ?? message.senderName ?? message.senderMeta?.name ?? 'Assistant'}` }; }; return html`
${ mobileSheet ? html`

Example storefront

{ event.currentTarget.textContent = 'Products opened'; }} > Browse products
${surface === 'ai-mode' ? html`` : ''}` : '' }
${headerStart ?? ''} ${surface === 'admin' ? '' : html`S`} ${title ?? (surface === 'admin' ? 'Customer conversation' : strings.header)}${surface === 'admin' ? html`Customer` : status == null ? '' : html`${status === 'online' ? 'Open' : 'Closed'}`} ${headerActions ?? ''} ${ surface === 'admin' ? '' : html` toggle(event, true)} >${IconClose()}` }
${content ?? ''} { 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 } ]); }} >
${ surface === 'admin' ? '' : surface === 'ai-mode' ? html`` : html`` }
`; } import '@avada/chatty-ui/elements/chatty-block-products.js'; const products = [ { id: 'tote', title: 'Canvas tote', amount: 24, price: '$24.00', compareAtPrice: '$32.00', image: 'https://chatty-ui-research.avada-tesla-chatty.workers.dev/fixtures/tote.svg' }, { id: 'cap', title: 'Cotton cap', amount: 18, price: '$18.00', image: 'https://chatty-ui-research.avada-tesla-chatty.workers.dev/fixtures/cap.svg', available: false }, { id: 'mug', title: 'Stoneware mug', amount: 16, price: '$16.00', image: 'https://chatty-ui-research.avada-tesla-chatty.workers.dev/fixtures/mug.svg', cartState: 'error', cartError: 'Could not add to cart' } ]; /** Builds a shopping thread with isolated host-owned fixture cart state. * @param {string} surface * @returns {Object} */ function cartPattern(surface) { const store = fixtureStore([ question, { id: 'products', senderType: 'bot', text: 'Here are three options for you.', blocks: [{type: 'products', data: {products}}] } ]); const add = event => { const product = event.detail.product; const update = cartState => store.setMessages( store.getState().messages.map(m => m.id !== 'products' ? m : { ...m, blocks: [ { type: 'products', data: { products: m.blocks[0].data.products.map(p => p.id === product.id ? {...p, cartState} : p ) } } ] } ) ); update('loading'); const finish = () => { update('added'); if (surface === 'ai-mode') store.setMessages([ ...store.getState().messages, { id: `receipt-${store.getState().messages.length}`, senderType: 'bot', blocks: [ { type: 'cart-confirmation', data: { receipts: [ {title: product.title, quantity: 1, linePrice: product.amount, currency: 'USD'} ] } } ] } ]); setTimeout(() => update('idle'), surface === 'classic' ? 2000 : 1650); }; if (matchMedia('(prefers-reduced-motion: reduce)').matches) finish(); else setTimeout(finish, 450); }; if (surface === 'admin') store.setMessages([ ...store.getState().messages, { id: 'receipt', senderType: 'bot', blocks: [ { type: 'cart-confirmation', data: {receipts: [{title: 'Canvas tote', quantity: 1, linePrice: 24, currency: 'USD'}]} } ] } ]); return html`
{ const line = store .getState() .messages.flatMap(message => message.blocks ?? []) .filter(block => block.type === 'cart-confirmation') .at(-1).data.receipts[0]; store.setMessages([ ...store.getState().messages, { id: `bag-${store.getState().messages.length}`, senderType: 'bot', text: `Your bag: ${line.title} × ${line.quantity} — ${new Intl.NumberFormat('en', {style: 'currency', currency: line.currency}).format(line.linePrice)}` } ]); }} > ${patternShell({surface, store})}
`; } export function StandardAdmin() { return cartPattern('admin'); } ``` Chọn ảnh/card → chi tiết: N/A trong preview. View similar: N/A trong preview; slot overlay của card nằm trong open button nên chưa hỗ trợ interactive overlay độc lập mà không lồng button. Cart action dùng fixture; Admin chỉ đọc. Quote/launcher navigation: N/A trong preview. ### Current Example (Current (React), being replaced) — `ChatProductCarousel` thật với ba card: giảm giá, giá thường, hết hàng. ```jsx import React from 'react'; import {ChatProductCarousel} from '@scripttag/v2/views/chat/ChatProductCarousel.jsx'; import {ChatNavigationContext} from '@scripttag/v2/views/chat/chatNavigationContext.js'; const product = (id, title, slug, image, price, compareAt, availableForSale = true) => ({ productId: `gid://shopify/Product/${id}`, title, url: `https://shop.example/products/${slug}`, image, imageAlt: title, availableForSale, currency: 'USD', prices: [price], compareAtPrices: compareAt ? [compareAt] : [], variantOptions: [`Default Title: ${id}1`] }); const products = [ product(101, 'Canvas tote bag', 'canvas-tote', '/fixtures/tote.svg', '$24.00', '$32.00'), product(102, 'Ceramic mug', 'ceramic-mug', '/fixtures/mug.svg', '$18.00'), product(103, 'Wool cap', 'wool-cap', '/fixtures/cap.svg', '$28.00', null, false) ]; export function Carousel() { return ( ); } ``` ## Classic ### Import / element #### ChatbotProductsMessage | Component / element | Import / file | Scope root | | --- | --- | --- | | `ChatbotProductsMessage` | import ChatbotProductsMessage from '@scripttag/v1/Parts/InsertProduct/ChatbotProductsMessage/ChatbotProductsMessage'; | .Avada-Faqs_Popup | ### Anatomy #### ChatbotProductsMessage | Part | Element | | --- | --- | | 1 | Nút `Avada-Faq_ChatbotProduct_SimilarAnchor` khi có anchor. | | 2 | Wrapper `Avada-Faq_ChatbotProduct_Wrapper` chứa `SlideButton` prev/next khi còn chỗ cuộn. | | 3 | Row cuộn `Avada-Faq_ChatbotProduct-Message_Wrapper`. | | 4 | Một `ProductCard` cho mỗi sản phẩm. | ### Placement / order #### ChatbotProductsMessage | Context | Order | | --- | --- | | Reply có sản phẩm | Anchor tương tự (nếu có) rồi wrapper: prev, row card, next. Trong card: ảnh với View similar, tiêu đề, rating, giá, nút thêm giỏ. | ### Props #### ChatbotProductsMessage | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `products` | array | Sản phẩm được nhắc tới | Không có | Chỉ nhắc tới sản phẩm có trong reply | | `isAdmin` | boolean | true / false | Không có | Admin: giá format theo shop, nút thêm giỏ khoá | | `wizard` | boolean | true / false | `false` | Preview wizard: nút không hoạt động | | `variantMode` | string | PRODUCT_CARD_VARIANT_MODE | `PRODUCT_CARD_VARIANT_MODE.FIRST_VARIANT` | Chọn variant hiển thị trên card | ### Sizes #### ChatbotProductsMessage | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | card | Theo nội dung | Info 10px 12px 12px | Info 10px | 14px | Theo Info; không đặt role ở wrapper | Ảnh là nút `inset: 0` phủ cả ảnh | Width 205px; `flex: 0 0 205px` | | row | Theo card | — | 8px | — | — | — | Cuộn ngang, `scroll-behavior: smooth`; ẩn scrollbar | ### Tokens #### ChatbotProductsMessage | Part | Token | Light | Dark | | --- | --- | --- | --- | | Card | `color`; `background`; `border` | #232323; rgba(255, 255, 255, 0.75); 1px #f2f2f2 | #ffffff; transparent; 1px #303030 | | Info | `background-color` | #ffffff | #303030 | ### States #### ChatbotProductsMessage | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Media focus-visible | keyboard | Outline 2px `var(--chatty-color-border-focus, #232323)`, offset -3px. | Native button | | Media disabled | Không mở được chi tiết | Con trỏ mặc định. | `disabled` | | Overlay hover / focus | pointer hoặc keyboard | Padding 6px 12px; chữ rộng tối đa 120px, opacity 1. | Native button | | Thêm giỏ bị khoá | Hết hàng, admin hoặc đang busy | `isAddToCartDisabled`; nút disabled. | `disabled` | ### Behaviour #### ChatbotProductsMessage | Interaction | Result | | --- | --- | | Chọn ảnh | Mở chi tiết trong chat khi không `disableProductDetail` và không cần báo giá; ngược lại mở link ở tab mới. | | Chọn tiêu đề | Link `target="_blank"` mở trang sản phẩm. | | View similar | Gửi tin nhắn tìm sản phẩm tương tự; admin không kích hoạt. | ### Copy #### ChatbotProductsMessage | String | i18n key | Where | | --- | --- | --- | | Similar to | Similar to | Anchor, khi có findSimilar | | View similar | View similar | Nút overlay trên ảnh card | | Out of stock | Out of stock | Tooltip nút thêm giỏ | ### Source #### ChatbotProductsMessage | File | Evidence | | --- | --- | | | Carousel và card | | | Card markup | | | Card style | ## AI Mode ### Import / element #### ChatProductCarousel | Component / element | Import / file | Scope root | | --- | --- | --- | | `ChatProductCarousel` | @scripttag/v2/views/chat/ChatProductCarousel.jsx | .chatty-ai-mode[data-theme] | #### ProductCard | Component / element | Import / file | Scope root | | --- | --- | --- | | `ProductCard` | @scripttag/v2/ui/ProductCard.jsx | .chatty-ai-mode[data-theme] | ### Anatomy #### ChatProductCarousel | Part | Element | | --- | --- | | 1 | Anchor `chatty-similar-anchor` khi có nguồn tương tự. | | 2 | `Carousel` với class `chatty-chat-products`. | | 3 | Mỗi sản phẩm là `ProductCard` với `AddToCartButton`. | #### ProductCard | Part | Element | | --- | --- | | 1 | Root `chatty-product-card`. | | 2 | Vùng mở chi tiết `chatty-product-card-link` với `role="button"`. | | 3 | Media `chatty-product-card-media` với `ProductImage`. | | 4 | Tên `chatty-clamp-2`; rating tuỳ chọn. | | 5 | Hàng giá `PriceRow`. | | 6 | Slot `action` và `footer` dưới thông tin. | ### Placement / order #### ChatProductCarousel | Context | Order | | --- | --- | | Reply có sản phẩm | Carousel render theo thứ tự sản phẩm được nhắc trong nội dung reply; không có sản phẩm được nhắc thì không render. | #### ProductCard | Context | Order | | --- | --- | | Trong carousel | Link (media, tên, rating, giá) rồi action rồi footer. | ### Props #### ChatProductCarousel | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `messageId` | string | Id của reply | Không có | Gắn vào tracking click card | | `products` | array | Sản phẩm của reply | Không có | Rỗng thì trả null | | `tracksAiLinks` | boolean | true / false | `false` | AI chọn sản phẩm: click sang store tính là AI link | #### ProductCard | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `product` | object | Trường hiển thị của card | Bắt buộc | Có id, handle, name, img, price | | `onOpen` | function | Nhận trigger của card | Bắt buộc | Gọi khi click hoặc Enter/Space | | `selected` | boolean | true / false | `false` | Thêm class `is-selected` | | `skeleton` | boolean | true / false | `false` | Cùng box với card đã tải | ### Sizes #### ChatProductCarousel | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | card | Theo nội dung | Theo ProductCard | `--card-gap` 12px | Theo ProductCard | Theo ProductCard | Card là vùng nhấn | Width 184px; `flex: 0 0 184px` | | track | Theo card | — | 12px | — | — | Cuộn ngang `scroll-snap-type: x mandatory` | Mobile ẩn arrow | | arrow | Theo `--icon-btn-size` | — | 8px | — | — | 32px desktop | Mobile ẩn arrow | #### ProductCard | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | card | Theo nội dung | 10px | 8px | `--radius-card` (20px) | Role theo type của surface | Vùng link phủ media, tên, giá | Width 184px do carousel | | media | Tỉ lệ `aspect-ratio: 4 / 5` | — | — | 14px | — | Thuộc vùng link | Ảnh `object-fit: contain` | ### Tokens #### ChatProductCarousel | Part | Token | Light | Dark | | --- | --- | --- | --- | | Khoảng cách card | `--card-gap` | 12px | Same | | Arrow | `--icon-btn-size` | 32px | Same; mobile ẩn | | Arrow shadow | `--shadow-2` | Theo foundation của AI Mode | Same | #### ProductCard | Part | Token | Light | Dark | | --- | --- | --- | --- | | Viền khi chọn | `--accent` | Merchant accent theo foundation | Same | | Màu chữ | `color: inherit` | Kế thừa từ surface | Kế thừa từ surface | ### States #### ChatProductCarousel | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Arrow active | pointer down | `scale(0.94)`; giữ `translateY(-50%)` trên desktop. | Native button | | Arrow chỉ khi còn chỗ cuộn | Có thể cuộn tới mốc | Nút prev hoặc next hiện. | `aria-label` Previous | #### ProductCard | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Hover (hover: hover và pointer: fine) | pointer | Card `translateY(-2px)`; ảnh `scale(1.03)`; tên gạch chân. | Không thêm ARIA | | Focus-visible | keyboard | Outline 2px `var(--chatty-color-border-focus)`, offset 2px. | Native focus | | Selected | `selected` true | Viền `--accent`. | Class `is-selected` | | Reduced motion | `prefers-reduced-motion: reduce` | Card `animation: none`; ảnh `transition: none`. | Không đổi | ### Behaviour #### ChatProductCarousel | Interaction | Result | | --- | --- | | Chọn card | Có handle thì mở chi tiết trong panel; không thì mở trang store. | | Launcher bị ẩn và không có navigate | Mở trang store cùng tab, không bật panel. | | Nút thêm giỏ | Thêm thẳng khi có variant duy nhất và còn hàng; không thì mở chi tiết. | #### ProductCard | Interaction | Result | | --- | --- | | Click hoặc Enter/Space | Gọi `onOpen` với trigger card. | | Tên dài | Tên bị cắt ở 2 dòng bằng `chatty-clamp-2`. | ### Copy #### ChatProductCarousel | String | i18n key | Where | | --- | --- | --- | | Similar to | Similar to | Anchor nguồn tương tự | | Previous | Previous | `aria-label` nút prev | #### ProductCard | String | i18n key | Where | | --- | --- | --- | | View product | View product | `aria-label` của vùng link, kèm tên sản phẩm | ### Source #### ChatProductCarousel | File | Evidence | | --- | --- | | | Carousel và card | | | Layout carousel | | | Caller trong thread | #### ProductCard | File | Evidence | | --- | --- | | | Markup card | | | Style card | | | Media và interaction dùng chung | ## Admin ### Import / element #### ChatbotProductsBlock | Component / element | Import / file | Scope root | | --- | --- | --- | | `ChatbotProductsBlock` | @assets/pages/InboxManagement/v2/blocks/ChatbotProductsBlock.jsx | .inbox-v2 | ### Anatomy #### ChatbotProductsBlock | Part | Element | | --- | --- | | 1 | Render lại `ChatbotProductsMessage` với `isAdmin`. | | 2 | Nút `Avada-Faq_ChatbotProduct_SimilarAnchor` khi có anchor. | | 3 | Wrapper `Avada-Faq_ChatbotProduct_Wrapper` chứa `SlideButton` prev/next khi còn chỗ cuộn. | | 4 | Row cuộn `Avada-Faq_ChatbotProduct-Message_Wrapper`. | | 5 | Một `ProductCard` cho mỗi sản phẩm. | ### Placement / order #### ChatbotProductsBlock | Context | Order | | --- | --- | | Block products trong inbox | Trả null khi không có sản phẩm; ngược lại cùng thứ tự carousel như Classic. | ### Props #### ChatbotProductsBlock | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `block` | object | `block?.products` | Bắt buộc | Danh sách sản phẩm của block | | `vm` | object | `isAdminViewer(vm)` | Bắt buộc | Truyền `isAdmin` cho carousel | ### Sizes #### ChatbotProductsBlock | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | card | Theo nội dung | Info 10px 12px 12px | Info 10px | 14px | Theo Info; không đặt role ở wrapper | Ảnh là nút `inset: 0` phủ cả ảnh | Width 205px; `flex: 0 0 205px` | | row | Theo card | — | 8px | — | — | — | Cuộn ngang, `scroll-behavior: smooth`; ẩn scrollbar | ### Tokens #### ChatbotProductsBlock | Part | Token | Light | Dark | | --- | --- | --- | --- | | Card | `color`; `background`; `border` | #232323; rgba(255, 255, 255, 0.75); 1px #f2f2f2 | No Dark skin | | Info | `background-color` | #ffffff | No Dark skin | ### States #### ChatbotProductsBlock | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Media focus-visible | keyboard | Outline 2px `var(--chatty-color-border-focus, #232323)`, offset -3px. | Native button | | Media disabled | Không mở được chi tiết | Con trỏ mặc định. | `disabled` | | Overlay hover / focus | pointer hoặc keyboard | Padding 6px 12px; chữ rộng tối đa 120px, opacity 1. | Native button | | Thêm giỏ bị khoá | Hết hàng, admin hoặc đang busy | `isAddToCartDisabled`; nút disabled. | `disabled` | ### Behaviour #### ChatbotProductsBlock | Interaction | Result | | --- | --- | | Chọn ảnh | Mở chi tiết trong chat khi không `disableProductDetail` và không cần báo giá; ngược lại mở link ở tab mới. | | Chọn tiêu đề | Link `target="_blank"` mở trang sản phẩm. | | View similar | Gửi tin nhắn tìm sản phẩm tương tự; admin không kích hoạt. | ### Copy #### ChatbotProductsBlock | String | i18n key | Where | | --- | --- | --- | | Similar to | Similar to | Anchor, khi có findSimilar | | View similar | View similar | Nút overlay trên ảnh card | | Out of stock | Out of stock | Tooltip nút thêm giỏ | ### Source #### ChatbotProductsBlock | File | Evidence | | --- | --- | | | Block inbox | | | Carousel và card | | | Card style | ## Do / Don't Do: nêu ngay trong reply vì sao từng sản phẩm phù hợp rồi mới tới carousel. Don't: dựng carousel cho sản phẩm reply không nhắc tới. ## Accessibility | Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio | | --- | --- | --- | --- | --- | | Classic | Nút ảnh có `aria-label` theo tên sản phẩm | Nút native; focus ring theo States | Không có | Light Measured(#232323 / #ffffff = 15.72:1); Dark Measured(#ffffff / #303030 = 13.20:1) | | AI Mode | Vùng link có `role="button"` và `aria-label` | `tabIndex` 0; Enter hoặc Space mở card | Không có | Kế thừa `color: inherit` từ surface | | Admin | Giống Classic | Nút ảnh native; nút thêm giỏ disabled | Không có | Light Measured(#232323 / #ffffff = 15.72:1) | ## Target ```target | Surface | Now | Target | | --- | --- | --- | | Classic | Card 205px | Not in code yet — build with the body values. Target: card 184px như AI Mode để một quy tắc dùng cho cả ba surface. | | Admin | Card 205px | Not in code yet — build with the body values. Target: card 184px như AI Mode, cùng carousel Classic. | ``` --- # Resolved / reopened Dòng resolved và reopened trong thread của nhân viên, và việc view khách trong inbox bỏ các dòng đó. ## Key rules - Admin: resolve và reopen hiện thành một dòng centered, chữ #616161, theo nhãn của ActivityBlock; không có avatar và không có bubble nền. - Admin: view khách trong inbox bỏ mọi activity qua `filterViewerMessages`, nên khách không thấy resolved hay reopened ở đó. - Admin: activity có text do backend viết thì dùng text đó thay cho nhãn mặc định. ## Use when / Avoid Dùng khi nhân viên cần thấy vòng đời hội thoại trong thread. Trang này chỉ mô tả inbox; storefront có đường render riêng, chưa được mô tả ở đây. ### Use instead | Component | Use when | | --- | --- | | `ActivityBlock` | Dòng sự kiện hệ thống (resolved, reopened, joined, left, auto-resolved). | | `filterViewerMessages` | Lọc tin theo người xem; bỏ activity khi người xem là khách. | ## Entry points | Surface | Owner | | --- | --- | | Admin | Block registry map activity sang `ActivityBlock` | | Admin | WidgetV2Messages gọi `filterViewerMessages` với viewer khách | ## Flow | Surface | Step | Trigger | UI shown | Component | Copy + i18n key | Timing | | --- | --- | --- | --- | --- | --- | --- | | Admin | Hiện sự kiện | Message có activity | Dòng centered với nhãn | ActivityBlock | Conversation resolved / Conversation reopened (literal trong LABELS) | Theo realtime của thread | | Admin | View khách | Người xem là customer | Activity bị bỏ khỏi danh sách | filterViewerMessages | Không có chữ | Tính khi render | ## Edge cases | Surface | Case | Behaviour | | --- | --- | --- | | Admin | Activity mang text do backend viết | Hiện text đó thay cho nhãn mặc định | | Admin | Text bắt đầu bằng was | Thêm This conversation phía trước để thành câu đầy đủ | | Admin | Verb không có trong LABELS | Hiện nguyên verb | ## Live preview ### Standard Example (Standard) — Thread Standard dùng fixture cục bộ. ```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`A${content.sender ?? message.senderName ?? message.senderMeta?.name ?? 'Assistant'}` }; }; return html`
${ mobileSheet ? html`

Example storefront

{ event.currentTarget.textContent = 'Products opened'; }} > Browse products
${surface === 'ai-mode' ? html`` : ''}` : '' }
${headerStart ?? ''} ${surface === 'admin' ? '' : html`S`} ${title ?? (surface === 'admin' ? 'Customer conversation' : strings.header)}${surface === 'admin' ? html`Customer` : status == null ? '' : html`${status === 'online' ? 'Open' : 'Closed'}`} ${headerActions ?? ''} ${ surface === 'admin' ? '' : html` toggle(event, true)} >${IconClose()}` }
${content ?? ''} { 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 } ]); }} >
${ surface === 'admin' ? '' : surface === 'ai-mode' ? html`` : html`` }
`; } export function Standard() { const store = fixtureStore([ {...question, senderMeta: {name: 'Sam Taylor'}}, { id: 'resolved', senderType: 'system', layout: 'centered', text: 'Conversation resolved', hasEventTime: false } ]); return patternShell({ surface: 'admin', store, title: 'Sam Taylor', headerActions: html`Resolved { const button = event.currentTarget; button.disabled = true; store.setMessages([ ...store.getState().messages, { id: 'reopened', senderType: 'system', layout: 'centered', text: 'Conversation reopened', hasEventTime: false } ]); const status = button .closest('[data-pattern-actions]') .querySelector('[data-pattern-resolution]'); status.textContent = 'Conversation reopened'; button.remove(); status.focus({preventScroll: true}); }} >Reopen` }); } ``` Reopen giả lập event realtime để append activity, không gọi server. View khách: N/A trong preview (trang Admin). Backend override/unknown verb: N/A trong preview. ### Current Example (Current (React), being replaced) — ActivityBlock thật với ba activity; styling centered nằm ở MessageFrame nên không có trong specimen. ```jsx import React from 'react'; import {ActivityBlock} from '@assets/pages/InboxManagement/v2/blocks/ActivityBlock.jsx'; export function Labels() { return (


); } ``` ## Admin ### Import / element #### ActivityBlock | Component / element | Import / file | Scope root | | --- | --- | --- | | `ActivityBlock` | @assets/pages/InboxManagement/v2/blocks/ActivityBlock.jsx | .inbox-v2 .chatty-message--centered | #### Viewer filter | Component / element | Import / file | Scope root | | --- | --- | --- | | filterViewerMessages (hàm, không phải component) | @assets/pages/InboxManagement/v2/helpers/filterViewerMessages.js | .inbox-v2 | ### Anatomy #### ActivityBlock | Part | Element | | --- | --- | | 1 | Một span chứa nhãn hoặc text của activity. | #### Viewer filter | Part | Element | | --- | --- | | 1 | Hàm lọc danh sách tin theo người xem; không render UI. | ### Placement / order #### ActivityBlock | Context | Order | | --- | --- | | Thread | Dòng centered giữa thread, không có gutter. | #### Viewer filter | Context | Order | | --- | --- | | Not available | Caller quyết định thứ tự. | ### Props #### ActivityBlock | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `block` | object | activity, text | Caller | activity chọn nhãn; text ghi đè nhãn. | | `vm` | object | canonical message | Caller | vm.text là nguồn text dự phòng. | #### Viewer filter | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `viewerType` | string | agent / customer | Caller | customer bỏ activity và telemetry; mọi viewer dedupe theo id. | ### Sizes #### ActivityBlock | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | Dòng activity | — | 2px 12px | — | — | `body-small` | — | Không có size override mobile | #### Viewer filter | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | Not available | — | — | — | — | — | — | — | ### Tokens #### ActivityBlock | Part | Token | Light | Dark | | --- | --- | --- | --- | | Chữ | Not available | #616161 | No Dark skin | | Nền / viền | Not available | transparent; border 0 | No Dark skin | #### Viewer filter | Part | Token | Light | Dark | | --- | --- | --- | --- | | Not available | — | — | — | ### States #### ActivityBlock | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Mặc định | message có activity | Chữ #616161 căn giữa, nền transparent, không viền | Không thêm ARIA | #### Viewer filter | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Not available | — | — | — | ### Behaviour #### ActivityBlock | Interaction | Result | | --- | --- | | Chọn chữ | Dùng block.text hoặc vm.text nếu có; không thì nhãn theo activity; không có nhãn thì verb. | #### Viewer filter | Interaction | Result | | --- | --- | | Activity | Với người xem là customer, bỏ tin có activity (resolved, reopened, assigned). | | Telemetry | Với customer, bỏ tin isIntent và chatbot-skip-reply. | ### Copy #### ActivityBlock | String | i18n key | Where | | --- | --- | --- | | Conversation resolved | Không có i18n key (literal) | LABELS.resolved | | Conversation reopened | Không có i18n key (literal) | LABELS.reopened | | Conversation auto-resolved | Không có i18n key (literal) | LABELS auto-resolved | #### Viewer filter | String | i18n key | Where | | --- | --- | --- | | Not available | — | — | ### Source #### ActivityBlock | File | Evidence | | --- | --- | | | Nhãn và chọn chữ | | | Layout centered | #### Viewer filter | File | Evidence | | --- | --- | | | Hàm lọc | | | Caller view khách | ## Do / Don't Do: để nhân viên đọc resolve và reopen ngay trong thread bằng dòng centered. Don't: bắt buộc khách tạo thread mới vì hội thoại đã resolve; trang này không mô tả thao tác reopen ở server. ## Accessibility | Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio | | --- | --- | --- | --- | --- | | Admin | Span trong bubble centered, không có role riêng | Không focusable | Không có live region riêng | Không khai báo cặp màu trong cell | --- # Suggested questions Follow-up chip ngay dưới câu trả lời, theo code AI Mode đang chạy. ## Key rules - Follow-up là `button` dùng class `chatty-suggested-question`, xếp cột dưới câu trả lời với gap 8px. - Chip chỉ hiện khi không streaming, không lỗi và không ở chế độ human (`showSuggests`). - Mỗi lượt hoàn tất thay bộ chip cũ; không có suggestions thì không hiện chip nào. - Client không cắt số chip: số lượng do server trả về trong `suggestedQuestions`. ## Use when / Avoid Dùng sau một câu trả lời để khách hỏi tiếp bằng một chạm. Starter ở lần mở đầu thuộc pattern Welcome / first open. Classic không có implementation follow-up tương ứng trong source nên không nằm trong trang này. ### Use instead | Component | Use when | | --- | --- | | `button` | Follow-up dưới câu trả lời trong thread. | | `CommonlyAskedSection` | Starter ở thread mở đầu, trước tin nhắn đầu tiên của khách. | ## Entry points | Surface | Owner | | --- | --- | | AI Mode | `ChatThread` render nhóm chip trong `Presence` khi `showSuggests`. | ## Flow | Surface | Step | Trigger | UI shown | Component | Copy + i18n key | Timing | | --- | --- | --- | --- | --- | --- | --- | | AI Mode | Lượt trả lời hoàn tất | Server trả `suggestedQuestions` | Store giữ danh sách chip mới | Store `suggestedQuestions` | Server-provided | Khi lượt kết thúc | | AI Mode | Hiện chip | `showSuggests` true | Nhóm chip dưới câu trả lời | `button` | Server-provided | Theo `Presence` | | AI Mode | Click chip | Khách chọn một chip | Chip gửi như lượt hỏi mới | `button` | Server-provided | Khi click | | AI Mode | Lượt kế tiếp | Lượt mới kết thúc | Bộ chip cũ bị thay hoặc xóa | Store `suggestedQuestions` | Server-provided | Khi lượt kết thúc | ## Edge cases | Surface | Case | Behaviour | | --- | --- | --- | | AI Mode | Không có suggestions | Danh sách rỗng nên `showSuggests` false và không có chip | | AI Mode | Đang streaming, lỗi hoặc human mode | Chip ẩn | | AI Mode | Click khi lượt trước còn chạy | Bị bỏ qua và không tracking | | AI Mode | Label dài | Chip giữ max-width 100% và ngắt chữ bằng `overflow-wrap` | ## Live 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`A${content.sender ?? message.senderName ?? message.senderMeta?.name ?? 'Assistant'}` }; }; return html`
${ mobileSheet ? html`

Example storefront

{ event.currentTarget.textContent = 'Products opened'; }} > Browse products
${surface === 'ai-mode' ? html`` : ''}` : '' }
${headerStart ?? ''} ${surface === 'admin' ? '' : html`S`} ${title ?? (surface === 'admin' ? 'Customer conversation' : strings.header)}${surface === 'admin' ? html`Customer` : status == null ? '' : html`${status === 'online' ? 'Open' : 'Closed'}`} ${headerActions ?? ''} ${ surface === 'admin' ? '' : html` toggle(event, true)} >${IconClose()}` }
${content ?? ''} { 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 } ]); }} >
${ surface === 'admin' ? '' : surface === 'ai-mode' ? html`` : html`` }
`; } import '@avada/chatty-ui/elements/chatty-block-suggestions.js'; export function Standard({surface}) { const store = fixtureStore([ question, { id: 'answer', senderType: 'bot', text: 'The canvas tote is reusable.', blocks: [ {type: 'suggestions', data: {suggestions: ['What fits inside?', 'How do I wash it?']}} ] } ]); const reply = text => { const history = store .getState() .messages.map(message => message.blocks?.some(block => block.type === 'suggestions') ? {...message, blocks: message.blocks.filter(block => block.type !== 'suggestions')} : message ); store.setMessages([ ...history, { id: `followup-${history.length}`, senderType: 'bot', text: `You asked: “${text}”. Here is some more information.`, blocks: [{type: 'suggestions', data: {suggestions: ['Tell me about the material']}}] } ]); }; return html`
{ event.currentTarget.querySelector('chatty-composer').send(event.detail.text); }} > ${patternShell({surface, store, onSend: reply})}
`; } ``` Chip gửi như lượt hỏi mới; câu trả lời và bộ chip tiếp theo là fixture, không gọi AI. ### Current Example (Current (React), being replaced) — Nhóm chip đúng markup của `ChatThread`; dữ liệu cục bộ, không gọi mạng. ```jsx import {Presence} from '@avada/chatty-ui/primitives/Presence.jsx';
{suggestedQuestions.map(q => ( ))}
``` ## AI Mode ### Import / element #### Follow-up chip | Component / element | Import / file | Scope root | | --- | --- | --- | | `button` | | .chatty-ai-mode | ### Anatomy #### Follow-up chip | Part | Element | | --- | --- | | 1 | Nhóm `chatty-chat-suggests` chứa các chip. | | 2 | `button` với `chatty-chat-suggest` + `chatty-suggested-question`. | | 3 | `spanchatty-chat-suggest-text` giữ chữ câu hỏi. | ### Placement / order #### Follow-up chip | Context | Order | | --- | --- | | Thread viewport | Sau `AnswerError` và `ContinueWithAIButton`, trước `chatty-chat-spacer`. | | Nhóm chip | Xếp cột, căn đầu dòng, cách nội dung phía trên 16px. | ### Props #### Follow-up chip | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `suggestedQuestions` | string[] | Câu hỏi do server trả | [] | Không có cắt số lượng trong client; thay mới ở mỗi lượt hoàn tất. | ### Sizes #### Follow-up chip | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | Chip | min-height 32px | 5px 12px; mobile 10px theo block | 8px giữa các chip | 30px via `--radius-pill` | `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 | Native box, mobile min-height 44px | Mobile và pointer coarse tăng target | ### Tokens #### Follow-up chip | Part | Token | Light | Dark | | --- | --- | --- | --- | | Chữ chip | `--vib-2` | rgba(20,19,24,0.74) | rgba(255,255,255,0.74) | | Viền chip | `--glass-edge` | rgba(20,19,24,0.08) | rgba(255,255,255,0.12) | | Fill hover | `--fill-hover` | rgba(20,19,24,0.1) dưới 900px; rgba(255,255,255,0.92) từ min-width 900px | rgba(255,255,255,0.14) | | Focus ring | `--focus-ring` | color-mix(in srgb, var(--accent) 25%, transparent) | Same | | Bo góc | `--radius-pill` | 30px | Same | ### States #### Follow-up chip | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Rest | Chip hiển thị | Viền 1px `--glass-edge`, chữ `--vib-2`, nền trong suốt | `button` native, type button | | Hover | Con trỏ | Nền `--fill-hover` | Không thêm ARIA | | Focus-visible | Bàn phím | Outline 2px solid `--focus-ring`, `outline-offset` 2px | Native focus | | Disabled | Not available | Not available; chip không có prop disabled | Not available | ### Behaviour #### Follow-up chip | Interaction | Result | | --- | --- | | Click | `askSuggested` gửi chữ chip bằng `deliverTurn` như lượt hỏi thường. | | Chặn gửi | `canSendMessage` sai thì bỏ qua, không tracking. | | Tracking | `quick_reply_click` với chip_type follow_up. | | Hiện / ẩn | `Presence` theo `showSuggests`. | | Bàn phím | `button` native nhận Enter và Space. | ### Copy #### Follow-up chip | String | i18n key | Where | | --- | --- | --- | | Chữ chip | Server-provided | Phần tử của `suggestedQuestions` | ### Source #### Follow-up chip | File | Evidence | | --- | --- | | | Nhóm chip và `Presence` | | | Click gửi lượt hỏi | | | Điều kiện hiện chip | | | Layout nhóm chip | | | Chip material, size và focus | ## Do / Don't Do: viết câu hỏi ngắn có thể gửi trực tiếp như một lượt hỏi. Don't: dựng chip riêng bỏ qua `showSuggests`, hoặc giữ bộ cũ dưới câu trả lời không liên quan. ## Accessibility | Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio | | --- | --- | --- | --- | --- | | AI Mode | `button` native; tên accessible là chữ câu hỏi | Tab và Enter/Space theo `button` native; `askSuggested` không gọi hàm focus nào nên focus ở lại chip; outline 2px | Not available; `Presence` không thêm live region cho nhóm chip | Light Measured(rgba(20,19,24,0.74) / #f6f4f0 = 7.58:1); Dark Measured(rgba(255,255,255,0.74) / #131215 = 10.42:1) | --- # 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`A${content.sender ?? message.senderName ?? message.senderMeta?.name ?? 'Assistant'}` }; }; return html`
${ mobileSheet ? html`

Example storefront

{ event.currentTarget.textContent = 'Products opened'; }} > Browse products
${surface === 'ai-mode' ? html`` : ''}` : '' }
${headerStart ?? ''} ${surface === 'admin' ? '' : html`S`} ${title ?? (surface === 'admin' ? 'Customer conversation' : strings.header)}${surface === 'admin' ? html`Customer` : status == null ? '' : html`${status === 'online' ? 'Open' : 'Closed'}`} ${headerActions ?? ''} ${ surface === 'admin' ? '' : html` toggle(event, true)} >${IconClose()}` }
${content ?? ''} { 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 } ]); }} >
${ surface === 'admin' ? '' : surface === 'ai-mode' ? html`` : html`` }
`; } 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 (
); } export function Waiting() { const [ready] = useState(() => seed({messages: [question], awaitingReply: true, statusText: 'Finding your answer…'}) ); return ready ? : 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 (
); } export function Streaming() { const [ready] = useState(() => seed({messages: [question, reply(partial)]})); return ready ? : 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 (
); } export function ClassicWaiting() { return ; } ``` 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 (
); } export function ClassicReply() { return ; } ``` ## 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 | --- # Welcome / first open Lời chào và starter trong lần mở chat đầu, theo code AI Mode đang chạy. ## Key rules - Starter dùng `CommonlyAskedSection`: ở hub Home và ngay dưới welcome bubble khi thread còn trống. - Mỗi starter là một row cao tối thiểu 32px, bo `--radius-pill`, chữ `button-label`. - Starter đã được trả lời bị loại khỏi danh sách; không còn starter thì không render section. - Starter có answer của merchant trả lời bằng copy đó; không có answer thì gửi như một lượt hỏi AI. ## Use when / Avoid Dùng cho lúc khách chưa gửi tin nào: lời chào của merchant cộng với các câu hỏi gợi ý. Câu hỏi gợi ý sau một câu trả lời thuộc về pattern Suggested questions. Classic không có implementation tương ứng trong source nên không nằm trong trang này. ### Use instead | Component | Use when | | --- | --- | | `CommonlyAskedSection` | Starter ở hub Home theo cấu hình sectionsOrder. | | `CommonlyAskedSection` | Starter dưới welcome bubble khi thread còn ở trạng thái mở đầu. | ## Entry points | Surface | Owner | | --- | --- | | AI Mode | `CommonlyAskedSection` do `HomePage` ghép khi `suggestionFAQs` có phần tử. | | AI Mode | `CommonlyAskedSection` do `ChatThread` ghép sau welcome bubble khi `isOpening`. | ## Flow | Surface | Step | Trigger | UI shown | Component | Copy + i18n key | Timing | | --- | --- | --- | --- | --- | --- | --- | | AI Mode | Hub Home | Panel mở, `suggestionFAQs` không rỗng | Label Commonly Asked và các row starter | `CommonlyAskedSection` | Commonly Asked / Commonly Asked | Theo vòng render của caller | | AI Mode | Thread mở đầu | Có welcome bubble và `isOpening` | Welcome bubble rồi các row starter | `CommonlyAskedSection` | Commonly Asked / Commonly Asked | Theo vòng render của caller | | AI Mode | Khách chưa có thông tin liên hệ | `preForm?.mode` là guest | Pre-chat nudge, câu hỏi giữ trong `quickReply` | `CommonlyAskedSection` | Not available | Khi click | | AI Mode | Starter có answer | Click, `answer` có giá trị | Copy của merchant được trả qua `answerQuickReply` | `CommonlyAskedSection` | Copy do merchant viết | Khi click | | AI Mode | Starter không có answer | Click, `answer` trống | Gửi như lượt hỏi AI qua `deliverTurn` | `CommonlyAskedSection` | Copy do merchant viết | Khi click | ## Edge cases | Surface | Case | Behaviour | | --- | --- | --- | | AI Mode | Không có starter | Hub Home không render section khi `suggestionFAQs` rỗng | | AI Mode | Mọi starter đã trả lời | Section trả về null sau khi lọc `excludeQuestions` | | AI Mode | Click khi lượt trước còn chạy | Bị bỏ qua và không tracking, row không có trạng thái disabled | | AI Mode | Entry cũ không có answer | Rơi về lượt hỏi AI thay vì đọc FAQ | ## Live preview Hub Home, merchant answer, AI answer và pre-chat guest đều dùng fixture local; có thể tiếp tục bằng email hoặc Chat anonymously, không gọi API. 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`A${content.sender ?? message.senderName ?? message.senderMeta?.name ?? 'Assistant'}` }; }; return html`
${ mobileSheet ? html`

Example storefront

{ event.currentTarget.textContent = 'Products opened'; }} > Browse products
${surface === 'ai-mode' ? html`` : ''}` : '' }
${headerStart ?? ''} ${surface === 'admin' ? '' : html`S`} ${title ?? (surface === 'admin' ? 'Customer conversation' : strings.header)}${surface === 'admin' ? html`Customer` : status == null ? '' : html`${status === 'online' ? 'Open' : 'Closed'}`} ${headerActions ?? ''} ${ surface === 'admin' ? '' : html` toggle(event, true)} >${IconClose()}` }
${content ?? ''} { 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 } ]); }} >
${ surface === 'admin' ? '' : surface === 'ai-mode' ? html`` : html`` }
`; } import '@avada/chatty-ui/elements/chatty-block-suggestions.js'; import '@avada/chatty-ui/elements/pre-chat.js'; import '@avada/chatty-ui/elements/contact-form.js'; export function Standard({surface}) { const store = fixtureStore([ {id: 'welcome', senderType: 'bot', text: 'Hi! How can we help today?'} ]); let remaining = [ { id: 'delivery', question: 'When will my order arrive?', answer: 'Orders arrive in 3–5 business days.' }, {id: 'material', question: 'What is the tote made of?', answer: ''} ]; let contactKnown = false; let pending = null; const busy = () => store .getState() .messages.some( message => message.status === 'streaming' || message.blocks?.some(block => ['loading', 'reasoning'].includes(block.type)) ); const commit = (faq, owner) => { if (!faq || busy()) return; store.setMessages([ ...store.getState().messages, { id: `answer-${faq.id}`, senderType: 'bot', text: faq.answer || `You asked: “${faq.question}”. The tote uses sturdy cotton canvas.` } ]); owner.querySelector('chatty-contact-form').hidden = true; owner.querySelector('[data-welcome-invitation]').hidden = true; const invitation = owner.querySelector('chatty-pre-chat'); invitation.hidden = !invitation.email; const composer = owner.querySelector('chatty-composer'); composer.hidden = false; composer.renderRoot.querySelector('textarea').focus({preventScroll: true}); pending = null; }; const accept = (event, email = '') => { const owner = event.currentTarget.closest('[data-welcome]'); contactKnown = true; owner.querySelector('chatty-pre-chat').email = email; commit(pending, owner); }; return html`
${patternShell({ surface, store, title: 'Example store', content: html`

Commonly Asked

item.question)}}} @chatty-suggest=${event => { if (busy() || pending) return; const faq = remaining.find(item => item.question === event.detail.text); if (!faq) return; const owner = event.currentTarget.closest('[data-welcome]'); remaining = remaining.filter(item => item !== faq); const section = owner.querySelector('[data-starters]'); if (remaining.length) event.currentTarget.block = { data: {layout: 'row', suggestions: remaining.map(item => item.question)} }; else section.remove(); appendViewer(store, surface, faq.question); if (contactKnown) { commit(faq, owner); return; } pending = faq; const invitation = owner.querySelector('[data-welcome-invitation]'); invitation.hidden = false; invitation.querySelector('chatty-button').focus({preventScroll: true}); owner.querySelector('chatty-composer').hidden = true; }} >
` })}
`; } ``` ### Current Example (Current (React), being replaced) — `CommonlyAskedSection` thật với 3 starter cố định; dữ liệu cục bộ, không gọi mạng. ```jsx import {useContext} from 'react'; /** * Conversation starters, minus the ones already answered in this thread — classic filters the * same list on conversation.excludeQuestions so a clicked starter stops being offered. * @param {Array<{questionId: string, question: string, answer: string}>} faqs */ export function CommonlyAskedSection({faqs}) { const {excludeQuestions} = useChatStore(['excludeQuestions']); const remaining = faqs.filter(faq => !excludeQuestions?.includes(faq.questionId)); // The onboarding preview starts from the composer, so it offers no starter list. if (!remaining.length || getRuntimeHost()?.hideConversationStarters) return null; return (
{t('Commonly Asked')}
{remaining.map(faq => ( ))}
); } /** * A Commonly Asked chip — classic's conversation starter; the merchant writes the answer next to the question, so clicking replies with that copy rather than asking the AI, and entries with no answer fall back to a normal AI turn. * @param {string} questionId * @param {string} text * @param {string} answer merchant-authored answer copy, absent on older entries */ function ListRow({questionId, text, answer}) { const navigate = useChatNavigate(); const surface = useContext(ChatSurfaceContext); const ask = async () => { let {preForm} = chatStore.getState(); if (!preForm) { if (!canSendMessage(chatStore.getState())) return; await chatActions.showPreChatGate(); ({preForm} = chatStore.getState()); } if (preForm?.mode === 'guest') { chatStore.setState({ preForm: {...preForm, quickReply: {questionId, question: text, answer}, navigate} }); return chatActions.nudgePreForm({navigate, surface}); } // This row has no disabled state, so a click during a streaming turn is silently dropped — // tracking first would credit the chip with a turn that never left. if (!canSendMessage(chatStore.getState())) return; markLauncherEngaged(); trackEndCustomerEvent('quick_reply_click', { chip_type: 'conversation_starter', question_id: questionId, question: text }); // Only the answered branch is a FAQ read; the other becomes an AI turn and would inflate the report. // The chip's own copy, not the shopper's words, so it stays out of send_message like classic's starters. if (!answer) return chatActions.deliverTurn(text, {entryPoint: EVENT_ENTRY_POINT.QUICK_REPLY, navigate}); return chatActions.answerQuickReply({questionId, question: text, answer, navigate}); }; return ( ); } ``` Example (Current (React), being replaced) — `ChatThread` thật ở trạng thái mở đầu: welcome bubble rồi các starter. ```jsx import {CommonlyAskedSection} from '../components/CommonlyAskedSection.jsx'; {welcomeBubble && isOpening && } ``` ## AI Mode ### Import / element #### CommonlyAskedSection | Component / element | Import / file | Scope root | | --- | --- | --- | | `CommonlyAskedSection` | @scripttag/v2/components/CommonlyAskedSection.jsx | .chatty-ai-mode | ### Anatomy #### CommonlyAskedSection | Part | Element | | --- | --- | | 1 | Label `chatty-label` phía trên các row. | | 2 | Row `chatty-list-row` + `chatty-suggested-question`, chữ là câu hỏi của starter. | ### Placement / order #### CommonlyAskedSection | Context | Order | | --- | --- | | Hub Home | Theo thứ tự `sectionsOrder`; không render khi `suggestionFAQs` rỗng. | | Thread mở đầu | Ngay sau welcome bubble, chỉ khi `isOpening`. | | Section | Label rồi các row, xếp cột, căn đầu dòng. | ### Props #### CommonlyAskedSection | Prop | Type | Values | Default | Notes | | --- | --- | --- | --- | --- | | `faqs` | array | {questionId, question, answer} | Caller truyền | Danh sách bị lọc theo `excludeQuestions`; rỗng thì trả về null. | | `answer` | string | Copy merchant viết | Không có ở entry cũ | Có giá trị thì trả bằng `answerQuickReply`; trống thì gửi lượt AI. | ### Sizes #### CommonlyAskedSection | Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism | | --- | --- | --- | --- | --- | --- | --- | --- | | Row | min-height 32px | 5px 12px; mobile 10px theo block | 8px giữa các row | 30px via `--radius-pill` | `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 | Native box, mobile min-height 44px | Mobile và pointer coarse tăng target | ### Tokens #### CommonlyAskedSection | Part | Token | Light | Dark | | --- | --- | --- | --- | | Chữ row | `--vib-2` | rgba(20,19,24,0.74) | rgba(255,255,255,0.74) | | Viền row | `--glass-edge` | rgba(20,19,24,0.08) | rgba(255,255,255,0.12) | | Fill hover | `--fill-hover` | rgba(20,19,24,0.1) dưới 900px; rgba(255,255,255,0.92) từ min-width 900px | rgba(255,255,255,0.14) | | Viền hover | `--vib-3` | rgba(20,19,24,0.62) | rgba(255,255,255,0.62) | | Focus ring | `--focus-ring` | color-mix(in srgb, var(--accent) 25%, transparent) | Same | | Bo góc | `--radius-pill` | 30px | Same | ### States #### CommonlyAskedSection | State | Trigger | Visual change (values) | ARIA/attribute | | --- | --- | --- | --- | | Rest | Row hiển thị | Viền 1px `--glass-edge`, chữ `--vib-2`, nền trong suốt | Native button | | Hover | Con trỏ | Nền `--fill-hover`, viền `--vib-3` | Không thêm ARIA | | Focus-visible | Bàn phím | Outline 2px solid `--focus-ring`, `outline-offset` 2px | Native focus | | Disabled | Not available | Not available; row không có trạng thái disabled | Not available | ### Behaviour #### CommonlyAskedSection | Interaction | Result | | --- | --- | | Click khi chưa có pre-chat | `nudgePreForm` mở pre-chat với `quickReply` giữ câu hỏi. | | Click có answer | `answerQuickReply` trả copy của merchant, không hỏi AI. | | Click không có answer | `deliverTurn` gửi câu hỏi như lượt AI. | | Tracking | `quick_reply_click` với chip_type conversation_starter, chỉ sau khi chắc chắn gửi được. | | Bàn phím | Button native kích hoạt bằng Enter hoặc Space. | ### Copy #### CommonlyAskedSection | String | i18n key | Where | | --- | --- | --- | | Commonly Asked | Commonly Asked | Label của section qua `t` | | Câu hỏi starter | Merchant-owned | Trường `question` của mỗi entry | | Welcome message by chatbot | Welcome message by chatbot | Lời chào AI do merchant cấu hình `welcomeMessage` | | Welcome back, {{name}} | Welcome back, {{name}} | `HomeGreeting` cho khách đã đăng nhập hoặc đã verify | ### Source #### CommonlyAskedSection | File | Evidence | | --- | --- | | | Section, row và click flow | | | Section layout và hover | | | Row material, size và focus | | | Vị trí trong thread mở đầu | | | Vị trí ở hub Home | ## Do / Don't Do: dùng starter ngắn gửi được ngay, đúng với nội dung merchant sẵn sàng trả lời. Don't: tự dựng danh sách starter riêng ngoài `CommonlyAskedSection` hoặc giữ starter đã được trả lời. ## Accessibility | Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio | | --- | --- | --- | --- | --- | | AI Mode | Native button; tên accessible là câu hỏi của starter | Tab tới row, Enter/Space theo button native; `ask` không gọi hàm focus nào nên focus ở lại row; outline 2px | Not available; section không có live region | Light Measured(rgba(20,19,24,0.74) / #f6f4f0 = 7.58:1); Dark Measured(rgba(255,255,255,0.74) / #131215 = 10.42:1) | - .chatty-suggested-question