Key rules
- Classic: reset only the widget root; the merchant owns the document.
- Classic: lazy-load
ParentWidget, the widget owner. - AI Mode: show progress while waiting.
- AI Mode: use Markdown for streamed answers.
- AI Mode: map local motion to shared tokens.
On this page
Where tokens live
| Surface | File | Scope root | Theme switch |
|---|---|---|---|
| Classic | Shared motion sheet | .Avada- |
No Classic theme switch in this file |
| AI Mode | AI Mode foundation | .chatty- |
data- overrides the base variables |
How to apply
| Surface | API / class | Example |
|---|---|---|
| Classic | Lazy storefront panel | lazy( |
| AI Mode | Shared response primitive | Markdown receives animate for streamed text |
Keep the widget boundary
Controlled example: giữ style merchant bên ngoài root của widget; vế Don't cố ý bỏ phạm vi reset.
Show code
import React from 'react';
import {Button} from '@assets/components/ui';
import {ThinkingIndicator} from '@avada/chatty-ui/primitives/ThinkingIndicator.jsx';
import {Markdown} from '@avada/chatty-ui/primitives/Markdown.js';
const answer =
'**Trail Shell**\n\n- Chống mưa nhẹ, dễ gấp gọn.\n- Chọn cỡ theo lớp áo mặc bên trong.\n\nXem [bảng kích thước](/components/product-card/).';
function Pair({rule, children, caption}) {
return (
<figure
className="principles-example"
data-principle={rule}
aria-label={rule + ' controlled example'}
>
<style>{`
.principles-example{margin:0;color:var(--vib-1,#202223);font-size:14px;line-height:1.6}
.principles-example *{box-sizing:border-box;min-width:0}
.principles-example .comparison{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:18px}
.principles-example .comparison>section{border:1px solid #92929b;border-radius:12px;overflow:hidden;background:var(--bg-deep,#fff)}
.principles-example h4{font-size:15px;font-weight:600;margin:0;padding:12px 16px;border-bottom:1px solid #92929b}
.principles-example .sample{padding:16px;min-height:200px}
.principles-example .merchant{padding:16px;background:#f4f1e9;color:#202223;min-height:230px}
.principles-example .merchant-title{font-family:Georgia,serif;font-size:21px;margin:0 0 12px}
.principles-example .merchant-action{font:600 12px/1.5 sans-serif;letter-spacing:2px;text-transform:uppercase;border:1px solid #202223;background:transparent;padding:9px 12px;min-height:44px}
.principles-example .widget{margin-top:24px;padding:12px;border:1px solid #8b8b94;border-radius:8px;background:white;color:#202223;font:14px/1.5 sans-serif}
.principles-example .widget p{margin:0 0 10px}
.principles-example [data-scope-widget] :where(button,input,textarea,select){letter-spacing:normal;text-transform:none}
.principles-example .leaked-reset .merchant-action{letter-spacing:normal;text-transform:none}
.principles-example .question{max-width:85%;margin:0 0 24px auto;padding:10px 12px;border-radius:12px;background:#e5e5ec;color:#202223}
.principles-example .reply-slot{min-height:72px}
.principles-example pre{margin:0;font:inherit;white-space:pre-wrap;overflow-wrap:anywhere}
.principles-example figcaption{font-size:12px;line-height:1.6;margin-top:14px}
.principles-example a{color:inherit;text-decoration:underline}
.principles-example button:focus-visible,.principles-example a:focus-visible{outline:3px solid #786bdb;outline-offset:3px}
@media(max-width:620px){.principles-example .comparison{grid-template-columns:1fr}.principles-example .sample{min-height:180px}}
`}</style>
<div className="comparison">{children}</div>
<figcaption>
<strong>Controlled example.</strong> Đây là ví dụ dựng có kiểm soát bằng component thật,
không phải ảnh lỗi production. {caption}
</figcaption>
</figure>
);
}
export function Scope() {
return (
<Pair
rule="scope"
caption="Button từ source Classic; reset của widget giữ trong root. Vế Don't cố ý áp hai thuộc tính reset lên button của host để nhìn thấy phạm vi sai, không phải số đo CSS leak trên store thật."
>
<section data-verdict="do">
<h4>Do · Keep the merchant style</h4>
<div className="merchant">
<p className="merchant-title">Merchant collection</p>
<button className="merchant-action">Shop collection</button>
<div className="widget" data-scope-widget="">
<p>Chatty widget</p>
<Button className="Avada-Faqs_Primary-Button">Send</Button>
</div>
</div>
</section>
<section data-verdict="dont">
<h4>Don't · Reset the store</h4>
<div className="merchant leaked-reset">
<p className="merchant-title">Merchant collection</p>
<button className="merchant-action">Shop collection</button>
<div className="widget">
<p>Chatty widget</p>
<Button className="Avada-Faqs_Primary-Button">Send</Button>
</div>
</div>
</section>
</Pair>
);
}Load the owner on demand
Số đo A/B/C đã có từ SEO: main thread của script Chatty, không phải chi phí riêng ParentWidget. Điều kiện tải khác nhau; không quy mọi chênh lệch cho lazy-load.
Show code
import React, {useEffect, useRef, useState} from 'react';
import {readMotionDuration} from '@avada/chatty-ui/primitives/surfaceMorph.js';
import {IconBag} from '@avada/chatty-ui/icons/chatIcons.jsx';
function Diagram({id, children}) {
return <figure data-rule-visual={id} style={{margin: 0, color: 'var(--vib-1, #25252a)', fontFamily: 'inherit'}}>
<style>{`
[data-rule-visual] * { box-sizing: border-box; }
[data-rule-visual] .rule-columns { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:16px; }
[data-rule-visual] .rule-stage { position:relative; height:230px; overflow:hidden; border:1px solid #85858b; border-radius:12px; background:var(--bg-deep, #fff); margin-top:10px; }
[data-rule-visual] .rule-store { padding:14px; font-size:12px; line-height:1.5; }
[data-rule-visual] .rule-product { display:flex; gap:8px; margin-top:12px; align-items:center; }
[data-rule-visual] .rule-image { width:36px; height:36px; flex:none; background:#d9d5ce; border-radius:4px; }
[data-rule-visual] .rule-panel { position:absolute; left:12px; bottom:12px; background:#4759a8; border:1px solid #c2c9ef; border-radius:16px; color:white; overflow:hidden; }
[data-rule-visual] .rule-panel span { display:block; width:130px; padding:10px; font-size:12px; }
[data-rule-visual] .rule-controls { display:flex; align-items:center; flex-wrap:wrap; gap:12px; margin-bottom:14px; }
[data-rule-visual] .rule-replay { font:inherit; color:inherit; background:transparent; padding:6px 14px; border:1px solid currentColor; border-radius:8px; cursor:pointer; }
[data-rule-visual] .rule-replay:focus-visible { outline:3px solid #657fdf; outline-offset:3px; }
[data-rule-visual] figcaption, [data-rule-visual] .rule-note { font-size:12px; line-height:1.55; margin-top:12px; }
[data-rule-visual] .rule-header-view { position:relative; height:150px; display:grid; place-items:center; border:1px solid #85858b; border-radius:12px; overflow:hidden; margin-top:12px; }
[data-rule-visual] .rule-header { position:relative; width:150px; height:72px; border:1px solid #85858b; border-radius:10px; display:flex; justify-content:center; align-items:center; }
[data-rule-visual] .rule-header:after { content:''; position:absolute; left:0; right:0; top:50%; border-top:1px dashed #b55c42; pointer-events:none; }
[data-rule-visual] .rule-header-control { position:relative; padding:0; border:0; background:transparent; color:inherit; width:48px; height:48px; display:grid; grid-auto-rows:min-content; align-content:center; justify-items:center; transform:scale(2); }
[data-rule-visual] .rule-header-control::before { content:''; height:6px; width:100%; }
[data-rule-visual] .rule-header-control[data-fixed]::before { position:absolute; inset:0; }
[data-rule-visual] .rule-header-control svg { display:block; width:22px; height:22px; }
[data-rule-visual] .rule-timeline { display:grid; grid-template-columns:100px minmax(0,1fr); gap:12px; align-items:start; margin:16px 0; font-size:12px; }
[data-rule-visual] .rule-track { display:flex; flex-wrap:wrap; gap:6px; align-items:center; }
[data-rule-visual] .rule-task { padding:8px; border:1px solid #85858b; border-radius:4px; }
[data-rule-visual] .rule-cost { display:block; height:16px; border-radius:3px; margin-top:8px; }
[data-rule-visual] .rule-resize-axis { position:relative; height:90px; margin-top:14px; font-size:12px; }
[data-rule-visual] .rule-resize-axis::before { content:''; position:absolute; top:32px; left:0; right:0; border-top:1px solid #85858b; }
[data-rule-visual] .rule-time-mark { position:absolute; top:24px; height:20px; border-left:1px dashed currentColor; }
[data-rule-visual] .rule-time-mark span { position:absolute; top:-19px; transform:translateX(-50%); }
[data-rule-visual] .rule-time-bar { position:absolute; top:34px; left:0; height:10px; border-radius:3px; }
[data-rule-visual] .rule-time-label { position:absolute; top:54px; left:0; right:0; line-height:1.4; }
[data-rule-visual] .rule-chart { display:grid; gap:8px; margin-top:14px; }
[data-rule-visual] .rule-metric-columns { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:8px; font-size:12px; text-align:center; }
[data-rule-visual] .rule-bar-track { height:110px; display:flex; align-items:end; justify-content:center; border-bottom:1px solid #85858b; }
[data-rule-visual] .rule-bar { width:70%; min-height:2px; background:#4759a8; border-radius:3px 3px 0 0; }
[data-rule-visual] .rule-bar-value { min-height:36px; display:flex; align-items:end; justify-content:center; }
@media(max-width:380px) { [data-rule-visual] .rule-columns { gap:8px; } [data-rule-visual] .rule-stage { height:240px; } }
@media(prefers-reduced-motion:reduce) { [data-rule-visual], [data-rule-visual] * { animation:none !important; transition:none !important; } }
`}</style>
{children}
</figure>;
}
function SurfaceComparison({resize = false}) {
const root = useRef(null);
const [run, setRun] = useState(0);
const played = useRef(0);
const [state, setState] = useState('Ready');
const [reduced, setReduced] = useState(false);
useEffect(() => {
const media = matchMedia('(prefers-reduced-motion: reduce)');
const update = () => setReduced(media.matches);
update();
media.addEventListener('change', update);
return () => media.removeEventListener('change', update);
}, []);
useEffect(() => {
if (!run) return;
if (played.current === run) {
setState('Ready');
return;
}
played.current = run;
const element = root.current;
const stages = [...element.querySelectorAll('.rule-stage')];
const panels = stages.map(stage => stage.querySelector('.rule-panel'));
const store = stages[0].querySelector('.rule-store');
const style = getComputedStyle(element);
const open = readMotionDuration({style, token: resize ? '--chatty-motion-duration-350' : '--chatty-motion-duration-400', fallback: resize ? 350 : 400});
const targetDuration = resize ? 280 : open;
const tailDelay = resize ? 206 : 0;
const close = readMotionDuration({style, token: '--chatty-motion-duration-350', fallback: 350});
const easing = style.getPropertyValue('--chatty-motion-ease-surface').trim() || 'cubic-bezier(0.2, 0, 0, 1)';
const startWidth = resize ? 94 : 54;
const startHeight = resize ? 102 : 38;
const widths = stages.map(stage => stage.clientWidth - 24);
const animations = [];
let cancelled = false;
let hold;
let releaseHold;
const pause = () => new Promise(resolve => { releaseHold = resolve; hold = setTimeout(resolve, 500); });
const animate = (node, frames, duration, delay = 0) => {
const animation = node.animate(frames, {duration, delay, easing, fill: 'forwards'});
animations.push(animation);
return animation.finished;
};
const show = expanded => {
panels.forEach((panel, index) => Object.assign(panel.style, {
width: `${expanded ? widths[index] : startWidth}px`, height: `${expanded ? 150 : startHeight}px`, clipPath: 'none'
}));
};
const play = async () => {
setState('Opening');
if (reduced) {
show(true);
await pause();
if (cancelled) return;
show(false);
setState('Done');
return;
}
const geometry = [{width: `${startWidth}px`, height: `${startHeight}px`}, {width: `${widths[0]}px`, height: '150px'}];
Object.assign(panels[1].style, {width: `${widths[1]}px`, height: '150px'});
const clips = [
{clipPath: `inset(${150 - startHeight}px ${Math.max(0, widths[1] - startWidth)}px 0 0 round 16px)`},
{clipPath: 'inset(0px 0px 0px 0px round 16px)'}
];
await Promise.all([
animate(panels[0], geometry, open, tailDelay),
animate(panels[1], clips, targetDuration),
animate(store, [{transform: 'translateY(0px)'}, {transform: 'translateY(14px)'}], open, tailDelay)
]);
if (cancelled) return;
setState('Open');
await pause();
if (cancelled) return;
setState('Closing');
await Promise.all([
animate(panels[0], [...geometry].reverse(), close, tailDelay),
animate(panels[1], [...clips].reverse(), resize ? targetDuration : close),
animate(store, [{transform: 'translateY(14px)'}, {transform: 'translateY(0px)'}], close, tailDelay)
]);
if (!cancelled) setState('Done');
};
play().catch(error => { if (!cancelled) throw error; });
return () => {
cancelled = true;
clearTimeout(hold);
releaseHold?.();
animations.forEach(animation => animation.cancel());
store.style.transform = '';
show(false);
};
}, [run, reduced, resize]);
return <div ref={root} data-comparison={resize ? 'resize' : 'overlay'} data-run={run} data-state={state} data-reduced={reduced}>
<div className="rule-controls">
<button className="rule-replay" type="button" onClick={() => setRun(value => value + 1)}>Replay</button>
<span role="status">{state}{reduced ? ' · Reduced motion · static endpoints' : resize ? ' · Current tail 556 ms / Target 280 ms' : ' · 400 / 350 ms'}</span>
</div>
<div className="rule-columns">
{['width/height', 'clip-path'].map((label, index) => <div key={label}>
<strong>{resize ? index ? 'Target' : 'Current code' : label}</strong>
{resize && <div className="rule-note">{label}</div>}
<div className="rule-stage">
<div className="rule-store"><strong>Store</strong><p>Everyday essentials</p>{[0, 1].map(item => <div className="rule-product" key={item}><span className="rule-image" /><span>Ceramic collection<br />View product</span></div>)}</div>
<div className="rule-panel" style={{width: resize ? 94 : 54, height: resize ? 102 : 38}}><span>Chat</span></div>
</div>
{resize ? <>
<div className="rule-note">Time after input (ms), 0–600</div>
<div className="rule-resize-axis" aria-label="Time after input, milliseconds">
<span className="rule-time-mark" data-target-deadline="300" style={{left: '50%'}}><span>300</span></span>
<span className="rule-time-mark" data-input-window="500" style={{left: '83.333%'}}><span>500</span></span>
<span className="rule-time-bar" style={{width: index ? '46.667%' : '92.667%', background: index ? '#39765c' : '#a55740'}} />
<span className="rule-time-label">{index ? 'Target: 280 ms' : 'Observed end: 345–556 ms'}</span>
</div>
<div className="rule-note">{index ? 'Đích ≤300 ms kể cả đuôi; chưa phải code hiện tại.' : 'Layout shift: AI Mode bag 0.29–0.44; Classic Expand/Collapse 0.073–0.080.'}</div>
</> : <div className="rule-note">{index ? 'CLS 0.000–0.003' : 'CLS 0.67–0.74'}</div>}
</div>)}
</div>
<p className="rule-note">Mô phỏng phóng đại dịch chuyển để nhìn rõ hai cách đổi bounds; không phải phép đo CLS của preview. {resize ? 'Current code còn đổi width từng frame. CLS báo 0 không có nghĩa là không dịch: 23/24 lần bị loại do cửa sổ 500 ms sau input; một frame tại 556 ms đã bị tính vào CLS (0.0013). Preview minh họa biên kết thúc chậm nhất bằng clock 350 ms cộng khoảng chờ 206 ms, không phải trace frame gốc. Target 280 ms là mô phỏng đích ≤300 ms kể cả đuôi, không phải số đo production. Mobile không có resize morph; product detail chưa kiểm.' : 'CLS lấy từ số đo bàn giao trên store thật; hình chỉ minh họa cơ chế. Màu và nội dung panel được đơn giản hóa.'}</p>
</div>;
}
function Metric({title, values, unit, maximum}) {
return <section className="rule-chart" aria-label={title}>
<strong>{title}</strong>
<div className="rule-metric-columns">{values.map((value, index) => <div key={index}>
<span className="rule-bar-value">{value === null ? 'Not measured' : `${value}${unit}`}</span>
<div className="rule-bar-track">{value !== null && <div className="rule-bar" data-value={value} style={{height: `${value / maximum * 100}%`, background: ['#a55740', '#4759a8', '#39765c'][index]}} />}</div>
<span>{['A', 'B', 'C'][index]}</span>
</div>)}</div>
</section>;
}
export function Performance() {
return <Diagram id="performance">
<div className="rule-columns">
<Metric title="CLS · Store 1" values={[0.671, 0, null]} maximum={0.75} unit="" />
<Metric title="CLS · Store 2" values={[0.744, 0.003, null]} maximum={0.75} unit="" />
<Metric title="Main thread · Home" values={[485, 317, 163]} maximum={600} unit=" ms" />
<Metric title="Main thread · Product page" values={[580, 315, 197]} maximum={600} unit=" ms" />
</div>
<figcaption>A: trước tối ưu; B: clip-path + idle guard; C: defer boot. CLS: cold median, mỗi nhóm ba lượt, mobile rộng 390 pixel, CPU chậm bốn lần; chưa có CLS của C nên bỏ thanh C. Main thread là thời gian của script Chatty, không phải toàn trang: Home B ba lượt, Product page B năm lượt; C Home tám lượt, Product page ba lượt. Product page C dùng số cập nhật 197 ms (172–246), thay cho quan sát ban đầu 246 ms. Các nhóm có điều kiện tải khác nhau, không dùng biểu đồ để quy mọi chênh lệch cho một thay đổi. Đơn vị CLS và ms nằm ở biểu đồ riêng.</figcaption>
</Diagram>;
}Xem phương pháp và giới hạn số đo. Biểu đồ dùng số đã bàn giao, không đo trong frame này.
Show the waiting state
Controlled example: cùng thread, có hoặc cố ý không có ThinkingIndicator trong vùng chờ trả lời.
Show code
import React from 'react';
import {Button} from '@assets/components/ui';
import {ThinkingIndicator} from '@avada/chatty-ui/primitives/ThinkingIndicator.jsx';
import {Markdown} from '@avada/chatty-ui/primitives/Markdown.js';
const answer =
'**Trail Shell**\n\n- Chống mưa nhẹ, dễ gấp gọn.\n- Chọn cỡ theo lớp áo mặc bên trong.\n\nXem [bảng kích thước](/components/product-card/).';
function Pair({rule, children, caption}) {
return (
<figure
className="principles-example"
data-principle={rule}
aria-label={rule + ' controlled example'}
>
<style>{`
.principles-example{margin:0;color:var(--vib-1,#202223);font-size:14px;line-height:1.6}
.principles-example *{box-sizing:border-box;min-width:0}
.principles-example .comparison{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:18px}
.principles-example .comparison>section{border:1px solid #92929b;border-radius:12px;overflow:hidden;background:var(--bg-deep,#fff)}
.principles-example h4{font-size:15px;font-weight:600;margin:0;padding:12px 16px;border-bottom:1px solid #92929b}
.principles-example .sample{padding:16px;min-height:200px}
.principles-example .merchant{padding:16px;background:#f4f1e9;color:#202223;min-height:230px}
.principles-example .merchant-title{font-family:Georgia,serif;font-size:21px;margin:0 0 12px}
.principles-example .merchant-action{font:600 12px/1.5 sans-serif;letter-spacing:2px;text-transform:uppercase;border:1px solid #202223;background:transparent;padding:9px 12px;min-height:44px}
.principles-example .widget{margin-top:24px;padding:12px;border:1px solid #8b8b94;border-radius:8px;background:white;color:#202223;font:14px/1.5 sans-serif}
.principles-example .widget p{margin:0 0 10px}
.principles-example [data-scope-widget] :where(button,input,textarea,select){letter-spacing:normal;text-transform:none}
.principles-example .leaked-reset .merchant-action{letter-spacing:normal;text-transform:none}
.principles-example .question{max-width:85%;margin:0 0 24px auto;padding:10px 12px;border-radius:12px;background:#e5e5ec;color:#202223}
.principles-example .reply-slot{min-height:72px}
.principles-example pre{margin:0;font:inherit;white-space:pre-wrap;overflow-wrap:anywhere}
.principles-example figcaption{font-size:12px;line-height:1.6;margin-top:14px}
.principles-example a{color:inherit;text-decoration:underline}
.principles-example button:focus-visible,.principles-example a:focus-visible{outline:3px solid #786bdb;outline-offset:3px}
@media(max-width:620px){.principles-example .comparison{grid-template-columns:1fr}.principles-example .sample{min-height:180px}}
`}</style>
<div className="comparison">{children}</div>
<figcaption>
<strong>Controlled example.</strong> Đây là ví dụ dựng có kiểm soát bằng component thật,
không phải ảnh lỗi production. {caption}
</figcaption>
</figure>
);
}
export function Waiting() {
return (
<Pair
rule="waiting"
caption="Hai khung cùng câu hỏi và vị trí trả lời. Do dùng ThinkingIndicator của source; Don't cố ý bỏ phản hồi trong lúc chờ. Nhãn chỉ mô tả bước đang chạy, không hứa thời gian hoàn tất."
>
<section data-verdict="do">
<h4>Do · Show progress</h4>
<div className="sample chatty-chat-viewport">
<p className="question">Which jacket should I choose?</p>
<div className="reply-slot">
<ThinkingIndicator text="Finding your answer…" />
</div>
</div>
</section>
<section data-verdict="dont">
<h4>Don't · Leave the reply blank</h4>
<div className="sample chatty-chat-viewport">
<p className="question">Which jacket should I choose?</p>
<div className="reply-slot" />
</div>
</section>
</Pair>
);
}Render the answer structure
Controlled example: cùng nội dung qua Markdown thật hoặc in raw text, không đổi dữ liệu để tạo khác biệt.
Show code
import React from 'react';
import {Button} from '@assets/components/ui';
import {ThinkingIndicator} from '@avada/chatty-ui/primitives/ThinkingIndicator.jsx';
import {Markdown} from '@avada/chatty-ui/primitives/Markdown.js';
const answer =
'**Trail Shell**\n\n- Chống mưa nhẹ, dễ gấp gọn.\n- Chọn cỡ theo lớp áo mặc bên trong.\n\nXem [bảng kích thước](/components/product-card/).';
function Pair({rule, children, caption}) {
return (
<figure
className="principles-example"
data-principle={rule}
aria-label={rule + ' controlled example'}
>
<style>{`
.principles-example{margin:0;color:var(--vib-1,#202223);font-size:14px;line-height:1.6}
.principles-example *{box-sizing:border-box;min-width:0}
.principles-example .comparison{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:18px}
.principles-example .comparison>section{border:1px solid #92929b;border-radius:12px;overflow:hidden;background:var(--bg-deep,#fff)}
.principles-example h4{font-size:15px;font-weight:600;margin:0;padding:12px 16px;border-bottom:1px solid #92929b}
.principles-example .sample{padding:16px;min-height:200px}
.principles-example .merchant{padding:16px;background:#f4f1e9;color:#202223;min-height:230px}
.principles-example .merchant-title{font-family:Georgia,serif;font-size:21px;margin:0 0 12px}
.principles-example .merchant-action{font:600 12px/1.5 sans-serif;letter-spacing:2px;text-transform:uppercase;border:1px solid #202223;background:transparent;padding:9px 12px;min-height:44px}
.principles-example .widget{margin-top:24px;padding:12px;border:1px solid #8b8b94;border-radius:8px;background:white;color:#202223;font:14px/1.5 sans-serif}
.principles-example .widget p{margin:0 0 10px}
.principles-example [data-scope-widget] :where(button,input,textarea,select){letter-spacing:normal;text-transform:none}
.principles-example .leaked-reset .merchant-action{letter-spacing:normal;text-transform:none}
.principles-example .question{max-width:85%;margin:0 0 24px auto;padding:10px 12px;border-radius:12px;background:#e5e5ec;color:#202223}
.principles-example .reply-slot{min-height:72px}
.principles-example pre{margin:0;font:inherit;white-space:pre-wrap;overflow-wrap:anywhere}
.principles-example figcaption{font-size:12px;line-height:1.6;margin-top:14px}
.principles-example a{color:inherit;text-decoration:underline}
.principles-example button:focus-visible,.principles-example a:focus-visible{outline:3px solid #786bdb;outline-offset:3px}
@media(max-width:620px){.principles-example .comparison{grid-template-columns:1fr}.principles-example .sample{min-height:180px}}
`}</style>
<div className="comparison">{children}</div>
<figcaption>
<strong>Controlled example.</strong> Đây là ví dụ dựng có kiểm soát bằng component thật,
không phải ảnh lỗi production. {caption}
</figcaption>
</figure>
);
}
export function MarkdownPair() {
return (
<Pair
rule="markdown"
caption="Cùng một nội dung: Do đi qua Markdown của source với animate; Don't cố ý in raw text nên lộ cú pháp. Đây là nội dung giữ cố định, không mô phỏng tốc độ mạng hay đo thời gian stream."
>
<section data-verdict="do">
<h4>Do · Render Markdown</h4>
<div className="sample" data-markdown-rendered="">
<Markdown text={answer} animate />
</div>
</section>
<section data-verdict="dont">
<h4>Don't · Print raw text</h4>
<div className="sample">
<pre data-markdown-raw="">{answer}</pre>
</div>
</section>
</Pair>
);
}Use shared motion
Preview Overlay từ Motion dùng nguồn shared motion. CLS là số đo trước/sau đã bàn giao, không phải phép đo trên ví dụ dựng này.
Show code
import React, {useEffect, useRef, useState} from 'react';
import {readMotionDuration} from '@avada/chatty-ui/primitives/surfaceMorph.js';
import {IconBag} from '@avada/chatty-ui/icons/chatIcons.jsx';
function Diagram({id, children}) {
return <figure data-rule-visual={id} style={{margin: 0, color: 'var(--vib-1, #25252a)', fontFamily: 'inherit'}}>
<style>{`
[data-rule-visual] * { box-sizing: border-box; }
[data-rule-visual] .rule-columns { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:16px; }
[data-rule-visual] .rule-stage { position:relative; height:230px; overflow:hidden; border:1px solid #85858b; border-radius:12px; background:var(--bg-deep, #fff); margin-top:10px; }
[data-rule-visual] .rule-store { padding:14px; font-size:12px; line-height:1.5; }
[data-rule-visual] .rule-product { display:flex; gap:8px; margin-top:12px; align-items:center; }
[data-rule-visual] .rule-image { width:36px; height:36px; flex:none; background:#d9d5ce; border-radius:4px; }
[data-rule-visual] .rule-panel { position:absolute; left:12px; bottom:12px; background:#4759a8; border:1px solid #c2c9ef; border-radius:16px; color:white; overflow:hidden; }
[data-rule-visual] .rule-panel span { display:block; width:130px; padding:10px; font-size:12px; }
[data-rule-visual] .rule-controls { display:flex; align-items:center; flex-wrap:wrap; gap:12px; margin-bottom:14px; }
[data-rule-visual] .rule-replay { font:inherit; color:inherit; background:transparent; padding:6px 14px; border:1px solid currentColor; border-radius:8px; cursor:pointer; }
[data-rule-visual] .rule-replay:focus-visible { outline:3px solid #657fdf; outline-offset:3px; }
[data-rule-visual] figcaption, [data-rule-visual] .rule-note { font-size:12px; line-height:1.55; margin-top:12px; }
[data-rule-visual] .rule-header-view { position:relative; height:150px; display:grid; place-items:center; border:1px solid #85858b; border-radius:12px; overflow:hidden; margin-top:12px; }
[data-rule-visual] .rule-header { position:relative; width:150px; height:72px; border:1px solid #85858b; border-radius:10px; display:flex; justify-content:center; align-items:center; }
[data-rule-visual] .rule-header:after { content:''; position:absolute; left:0; right:0; top:50%; border-top:1px dashed #b55c42; pointer-events:none; }
[data-rule-visual] .rule-header-control { position:relative; padding:0; border:0; background:transparent; color:inherit; width:48px; height:48px; display:grid; grid-auto-rows:min-content; align-content:center; justify-items:center; transform:scale(2); }
[data-rule-visual] .rule-header-control::before { content:''; height:6px; width:100%; }
[data-rule-visual] .rule-header-control[data-fixed]::before { position:absolute; inset:0; }
[data-rule-visual] .rule-header-control svg { display:block; width:22px; height:22px; }
[data-rule-visual] .rule-timeline { display:grid; grid-template-columns:100px minmax(0,1fr); gap:12px; align-items:start; margin:16px 0; font-size:12px; }
[data-rule-visual] .rule-track { display:flex; flex-wrap:wrap; gap:6px; align-items:center; }
[data-rule-visual] .rule-task { padding:8px; border:1px solid #85858b; border-radius:4px; }
[data-rule-visual] .rule-cost { display:block; height:16px; border-radius:3px; margin-top:8px; }
[data-rule-visual] .rule-resize-axis { position:relative; height:90px; margin-top:14px; font-size:12px; }
[data-rule-visual] .rule-resize-axis::before { content:''; position:absolute; top:32px; left:0; right:0; border-top:1px solid #85858b; }
[data-rule-visual] .rule-time-mark { position:absolute; top:24px; height:20px; border-left:1px dashed currentColor; }
[data-rule-visual] .rule-time-mark span { position:absolute; top:-19px; transform:translateX(-50%); }
[data-rule-visual] .rule-time-bar { position:absolute; top:34px; left:0; height:10px; border-radius:3px; }
[data-rule-visual] .rule-time-label { position:absolute; top:54px; left:0; right:0; line-height:1.4; }
[data-rule-visual] .rule-chart { display:grid; gap:8px; margin-top:14px; }
[data-rule-visual] .rule-metric-columns { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:8px; font-size:12px; text-align:center; }
[data-rule-visual] .rule-bar-track { height:110px; display:flex; align-items:end; justify-content:center; border-bottom:1px solid #85858b; }
[data-rule-visual] .rule-bar { width:70%; min-height:2px; background:#4759a8; border-radius:3px 3px 0 0; }
[data-rule-visual] .rule-bar-value { min-height:36px; display:flex; align-items:end; justify-content:center; }
@media(max-width:380px) { [data-rule-visual] .rule-columns { gap:8px; } [data-rule-visual] .rule-stage { height:240px; } }
@media(prefers-reduced-motion:reduce) { [data-rule-visual], [data-rule-visual] * { animation:none !important; transition:none !important; } }
`}</style>
{children}
</figure>;
}
function SurfaceComparison({resize = false}) {
const root = useRef(null);
const [run, setRun] = useState(0);
const played = useRef(0);
const [state, setState] = useState('Ready');
const [reduced, setReduced] = useState(false);
useEffect(() => {
const media = matchMedia('(prefers-reduced-motion: reduce)');
const update = () => setReduced(media.matches);
update();
media.addEventListener('change', update);
return () => media.removeEventListener('change', update);
}, []);
useEffect(() => {
if (!run) return;
if (played.current === run) {
setState('Ready');
return;
}
played.current = run;
const element = root.current;
const stages = [...element.querySelectorAll('.rule-stage')];
const panels = stages.map(stage => stage.querySelector('.rule-panel'));
const store = stages[0].querySelector('.rule-store');
const style = getComputedStyle(element);
const open = readMotionDuration({style, token: resize ? '--chatty-motion-duration-350' : '--chatty-motion-duration-400', fallback: resize ? 350 : 400});
const targetDuration = resize ? 280 : open;
const tailDelay = resize ? 206 : 0;
const close = readMotionDuration({style, token: '--chatty-motion-duration-350', fallback: 350});
const easing = style.getPropertyValue('--chatty-motion-ease-surface').trim() || 'cubic-bezier(0.2, 0, 0, 1)';
const startWidth = resize ? 94 : 54;
const startHeight = resize ? 102 : 38;
const widths = stages.map(stage => stage.clientWidth - 24);
const animations = [];
let cancelled = false;
let hold;
let releaseHold;
const pause = () => new Promise(resolve => { releaseHold = resolve; hold = setTimeout(resolve, 500); });
const animate = (node, frames, duration, delay = 0) => {
const animation = node.animate(frames, {duration, delay, easing, fill: 'forwards'});
animations.push(animation);
return animation.finished;
};
const show = expanded => {
panels.forEach((panel, index) => Object.assign(panel.style, {
width: `${expanded ? widths[index] : startWidth}px`, height: `${expanded ? 150 : startHeight}px`, clipPath: 'none'
}));
};
const play = async () => {
setState('Opening');
if (reduced) {
show(true);
await pause();
if (cancelled) return;
show(false);
setState('Done');
return;
}
const geometry = [{width: `${startWidth}px`, height: `${startHeight}px`}, {width: `${widths[0]}px`, height: '150px'}];
Object.assign(panels[1].style, {width: `${widths[1]}px`, height: '150px'});
const clips = [
{clipPath: `inset(${150 - startHeight}px ${Math.max(0, widths[1] - startWidth)}px 0 0 round 16px)`},
{clipPath: 'inset(0px 0px 0px 0px round 16px)'}
];
await Promise.all([
animate(panels[0], geometry, open, tailDelay),
animate(panels[1], clips, targetDuration),
animate(store, [{transform: 'translateY(0px)'}, {transform: 'translateY(14px)'}], open, tailDelay)
]);
if (cancelled) return;
setState('Open');
await pause();
if (cancelled) return;
setState('Closing');
await Promise.all([
animate(panels[0], [...geometry].reverse(), close, tailDelay),
animate(panels[1], [...clips].reverse(), resize ? targetDuration : close),
animate(store, [{transform: 'translateY(14px)'}, {transform: 'translateY(0px)'}], close, tailDelay)
]);
if (!cancelled) setState('Done');
};
play().catch(error => { if (!cancelled) throw error; });
return () => {
cancelled = true;
clearTimeout(hold);
releaseHold?.();
animations.forEach(animation => animation.cancel());
store.style.transform = '';
show(false);
};
}, [run, reduced, resize]);
return <div ref={root} data-comparison={resize ? 'resize' : 'overlay'} data-run={run} data-state={state} data-reduced={reduced}>
<div className="rule-controls">
<button className="rule-replay" type="button" onClick={() => setRun(value => value + 1)}>Replay</button>
<span role="status">{state}{reduced ? ' · Reduced motion · static endpoints' : resize ? ' · Current tail 556 ms / Target 280 ms' : ' · 400 / 350 ms'}</span>
</div>
<div className="rule-columns">
{['width/height', 'clip-path'].map((label, index) => <div key={label}>
<strong>{resize ? index ? 'Target' : 'Current code' : label}</strong>
{resize && <div className="rule-note">{label}</div>}
<div className="rule-stage">
<div className="rule-store"><strong>Store</strong><p>Everyday essentials</p>{[0, 1].map(item => <div className="rule-product" key={item}><span className="rule-image" /><span>Ceramic collection<br />View product</span></div>)}</div>
<div className="rule-panel" style={{width: resize ? 94 : 54, height: resize ? 102 : 38}}><span>Chat</span></div>
</div>
{resize ? <>
<div className="rule-note">Time after input (ms), 0–600</div>
<div className="rule-resize-axis" aria-label="Time after input, milliseconds">
<span className="rule-time-mark" data-target-deadline="300" style={{left: '50%'}}><span>300</span></span>
<span className="rule-time-mark" data-input-window="500" style={{left: '83.333%'}}><span>500</span></span>
<span className="rule-time-bar" style={{width: index ? '46.667%' : '92.667%', background: index ? '#39765c' : '#a55740'}} />
<span className="rule-time-label">{index ? 'Target: 280 ms' : 'Observed end: 345–556 ms'}</span>
</div>
<div className="rule-note">{index ? 'Đích ≤300 ms kể cả đuôi; chưa phải code hiện tại.' : 'Layout shift: AI Mode bag 0.29–0.44; Classic Expand/Collapse 0.073–0.080.'}</div>
</> : <div className="rule-note">{index ? 'CLS 0.000–0.003' : 'CLS 0.67–0.74'}</div>}
</div>)}
</div>
<p className="rule-note">Mô phỏng phóng đại dịch chuyển để nhìn rõ hai cách đổi bounds; không phải phép đo CLS của preview. {resize ? 'Current code còn đổi width từng frame. CLS báo 0 không có nghĩa là không dịch: 23/24 lần bị loại do cửa sổ 500 ms sau input; một frame tại 556 ms đã bị tính vào CLS (0.0013). Preview minh họa biên kết thúc chậm nhất bằng clock 350 ms cộng khoảng chờ 206 ms, không phải trace frame gốc. Target 280 ms là mô phỏng đích ≤300 ms kể cả đuôi, không phải số đo production. Mobile không có resize morph; product detail chưa kiểm.' : 'CLS lấy từ số đo bàn giao trên store thật; hình chỉ minh họa cơ chế. Màu và nội dung panel được đơn giản hóa.'}</p>
</div>;
}
function Metric({title, values, unit, maximum}) {
return <section className="rule-chart" aria-label={title}>
<strong>{title}</strong>
<div className="rule-metric-columns">{values.map((value, index) => <div key={index}>
<span className="rule-bar-value">{value === null ? 'Not measured' : `${value}${unit}`}</span>
<div className="rule-bar-track">{value !== null && <div className="rule-bar" data-value={value} style={{height: `${value / maximum * 100}%`, background: ['#a55740', '#4759a8', '#39765c'][index]}} />}</div>
<span>{['A', 'B', 'C'][index]}</span>
</div>)}</div>
</section>;
}
export function Overlay() {
return <Diagram id="overlay"><SurfaceComparison /></Diagram>;
}Xem Overlay properties và giới hạn CLS. Không gán số đo production cho vế Don't của mô hình.
Element map
| Element | Surface | Role/Token | Light | Dark |
|---|---|---|---|---|
| Widget boundary | Classic | Scoped root | #Avada- |
Same root |
| Popup boundary | Classic | Fixed popup | .Avada- |
Same root |
| Waiting response | AI Mode | role="status" |
ThinkingIndicator state | Same semantics |
| Streamed response | AI Mode | Markdown |
Animated last block | Same semantics |
Tokens
Classic
Variables
| Part | Token | Light | Dark |
|---|---|---|---|
| Surface motion | - |
Shared motion alias | Same value |
AI Mode
Variables
| Part | Token | Light | Dark |
|---|---|---|---|
| State motion | - |
Shared motion alias | Shared motion alias |
Composed values
| Element | Surface | Light | Dark | Fallback |
|---|---|---|---|---|
| Classic panel | Classic | Lazy ParentWidget module |
— | DisplayManager has no fallback; ParentWidget uses an empty fallback for its inner widget |
| AI Mode reply | AI Mode | Streaming- |
Same primitive | Non-animate is false |
Copy-paste export
Classic
.Avada-Faqs_Popup {
position: fixed !important;
}
AI Mode
.chatty-ai-mode {
--dur-2: var(--chatty-motion-duration-200);
}
Contrast matrix
| Surface | Pair | Light ratio | Dark ratio |
|---|---|---|---|
| Classic | Motion aliases | Not a colour pair | Not a colour pair |
| AI Mode | State- |
Not a colour pair | Not a colour pair |