# Motion

Token duration, easing và timing đang chạy trên Classic, AI Mode và Admin.

## Key rules

- Classic: popup mở bằng `--chatty-motion-sheet-in` với `--chatty-motion-ease-out-emphasized` và đóng bằng `--chatty-motion-surface-out`.
- AI Mode: control đổi trạng thái bằng `--dur-2` và `--ease`; `--ease` là ease-out-emphasized, không phải ease-out.
- Admin: token đọc `--p-motion-duration-*` kèm fallback; đổi hội thoại giữ thread cũ tới mốc chờ của useCanonicalSync.
- AI Mode: reduced motion của launcher chỉ fade, không đổi hình học.
- Giá trị trong body là code hiện tại; đề xuất sửa nằm ở Target.

## Where tokens live

| Surface | File | Scope root | Theme switch |
| --- | --- | --- | --- |
| Classic | _motion.scss gọi qua foundations | .Avada-Faqs_Popup | Không đổi theo theme |
| AI Mode | _motion.scss gọi qua foundations; alias riêng trong foundation.scss | .chatty-ai-mode | Không đổi theo theme; mixin gọi ở cả Dark và Light |
| Admin | _motion.scss gọi qua foundations | .inbox-v2 | Chỉ một theme |

## How to apply

| Surface | API / class | Example |
| --- | --- | --- |
| Classic | Animation đọc token alias | animation: chatty-classic-open var(--chatty-motion-sheet-in) var(--chatty-motion-ease-out-emphasized) both; |
| AI Mode | Transition đọc alias riêng | transition: background var(--dur-2) var(--ease); |
| Admin | Sass mixin của chatty-ui | @include foundations.tokens(admin) |

**Overlay properties**

Surface nằm đè lên store (panel, morph launcher ↔ panel, popup) chỉ animate clip-path, transform, opacity cho hình học và độ hiện; không animate left/top/width/height. Đặt layout box cố định trước khi chạy đồng hồ, giữ duration và curve hiện có. Quy tắc này không có nghĩa mọi đường resize đã tuân thủ: xem Panel resize ở Target.

| Surface | API / class | Example |
| --- | --- | --- |
| AI Mode | Overlay properties · Launcher morph | Code hiện tại dùng clip-path trên layout box cố định; lớp màu vẫn được nội suy riêng. Mở 400 mili-giây, đóng 350 mili-giây, giữ curve surface. |
| AI Mode | Overlay properties · CLS evidence | Số đo đã bàn giao trên mobile rộng 390 pixel, CPU chậm bốn lần: CLS mỗi lần mở chat từ 0.67–0.74 xuống 0.000–0.003; morph là nguồn shift từ 12/12 lần xuống 0/12. Phần CLS còn lại do carousel bên trong panel ổn định sau mở; đây là số đo trước/sau, không phải cam kết CLS bằng không ở mọi store. |

Example — Hai cách đổi bounds trên store giả; số CLS là kết quả bàn giao, không đo từ mô hình.

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

## Element map

| Element | Surface | Role/Token | Light | Dark |
| --- | --- | --- | --- | --- |
| Popup mở | Classic | --chatty-motion-sheet-in; --chatty-motion-ease-out-emphasized | Animation chatty-classic-open | Same value |
| Popup đóng | Classic | --chatty-motion-surface-out; --chatty-motion-ease-out | Animation chatty-classic-close | Same value |
| Popup opacity | Classic | --chatty-motion-sheet-out; --chatty-motion-ease-in | Transition opacity | Same value |
| Control hover | AI Mode | --dur-2; --ease | Transition background, border-color, color, opacity; transform 0.18s | Same value |
| Launcher morph | AI Mode | --chatty-motion-ease-surface | Duration đọc token, mở khi focus và đóng khi không focus | Same value |
| Sidebar reduced motion | AI Mode | --aimode-sidebar-ms | 0ms khi prefers-reduced-motion | Same value |
| Thread đổi hội thoại | Admin | Không có token | Giữ thread cũ trong lúc tải rồi RESET; 300 mili-giây là mốc tối thiểu | No Dark skin |

## Tokens

### Classic

#### Motion durations

| Token | Duration | Use |
| --- | --- | --- |
| `--chatty-motion-duration-50` | Derived(50ms = duration(50)) | Bước của scale |
| `--chatty-motion-duration-100` | Derived(100ms = duration(100)) | Bước của scale |
| `--chatty-motion-duration-150` | Derived(150ms = duration(150)) | Bước của scale; Alias --chatty-motion-micro |
| `--chatty-motion-duration-200` | Derived(200ms = duration(200)) | Bước của scale |
| `--chatty-motion-duration-250` | Derived(250ms = duration(250)) | Bước của scale; Alias --chatty-motion-sheet-out |
| `--chatty-motion-duration-300` | Derived(300ms = duration(300)) | Bước của scale |
| `--chatty-motion-duration-350` | Derived(350ms = duration(350)) | Bước của scale; Alias --chatty-motion-surface-in và --chatty-motion-surface-out |
| `--chatty-motion-duration-400` | Derived(400ms = duration(400)) | Bước của scale; Alias --chatty-motion-sheet-in |
| `--chatty-motion-duration-450` | Derived(450ms = duration(450)) | Bước của scale |
| `--chatty-motion-duration-500` | Derived(500ms = duration(500)) | Bước của scale |

#### Motion easings

| Token | Curve | Use |
| --- | --- | --- |
| `--chatty-motion-ease-standard` | ease | Curve của scale |
| `--chatty-motion-ease-surface` | `cubic-bezier(0.2, 0, 0, 1)` | Curve của scale |
| `--chatty-motion-ease-in` | `cubic-bezier(0.42, 0, 1, 1)` | Curve của scale |
| `--chatty-motion-ease-out` | `cubic-bezier(0.19, 0.91, 0.38, 1)` | Curve của scale |
| `--chatty-motion-ease-in-out` | `cubic-bezier(0.42, 0, 0.58, 1)` | Curve của scale |
| `--chatty-motion-ease-out-emphasized` | `cubic-bezier(0.2, 0.8, 0, 1)` | Curve của scale |
| `--chatty-motion-ease-linear` | linear | Curve của scale |
| `--chatty-motion-ease-spring` | `cubic-bezier(0.34, 1.56, 0.64, 1)` | Curve của scale |

#### Variables

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Alias micro | `--chatty-motion-micro` | `var(--chatty-motion-duration-150)` | Same value |
| Alias surface-in | `--chatty-motion-surface-in` | `var(--chatty-motion-duration-350)` | Same value |
| Alias surface-out | `--chatty-motion-surface-out` | `var(--chatty-motion-duration-350)` | Same value |
| Alias sheet-in | `--chatty-motion-sheet-in` | `var(--chatty-motion-duration-400)` | Same value |
| Alias sheet-out | `--chatty-motion-sheet-out` | `var(--chatty-motion-duration-250)` | Same value |

### AI Mode

#### Motion durations

| Token | Duration | Use |
| --- | --- | --- |
| `--chatty-motion-duration-50` | Derived(50ms = duration(50)) | Bước của scale |
| `--chatty-motion-duration-100` | Derived(100ms = duration(100)) | Bước của scale |
| `--chatty-motion-duration-150` | Derived(150ms = duration(150)) | Bước của scale; Alias --chatty-motion-micro |
| `--chatty-motion-duration-200` | Derived(200ms = duration(200)) | Bước của scale |
| `--chatty-motion-duration-250` | Derived(250ms = duration(250)) | Bước của scale; Alias --chatty-motion-sheet-out |
| `--chatty-motion-duration-300` | Derived(300ms = duration(300)) | Bước của scale |
| `--chatty-motion-duration-350` | Derived(350ms = duration(350)) | Bước của scale; Alias --chatty-motion-surface-in và --chatty-motion-surface-out |
| `--chatty-motion-duration-400` | Derived(400ms = duration(400)) | Bước của scale; Alias --chatty-motion-sheet-in |
| `--chatty-motion-duration-450` | Derived(450ms = duration(450)) | Bước của scale |
| `--chatty-motion-duration-500` | Derived(500ms = duration(500)) | Bước của scale |

#### Motion easings

| Token | Curve | Use |
| --- | --- | --- |
| `--chatty-motion-ease-standard` | ease | Curve của scale |
| `--chatty-motion-ease-surface` | `cubic-bezier(0.2, 0, 0, 1)` | Curve của scale |
| `--chatty-motion-ease-in` | `cubic-bezier(0.42, 0, 1, 1)` | Curve của scale |
| `--chatty-motion-ease-out` | `cubic-bezier(0.19, 0.91, 0.38, 1)` | Curve của scale |
| `--chatty-motion-ease-in-out` | `cubic-bezier(0.42, 0, 0.58, 1)` | Curve của scale |
| `--chatty-motion-ease-out-emphasized` | `cubic-bezier(0.2, 0.8, 0, 1)` | Curve của scale |
| `--chatty-motion-ease-linear` | linear | Curve của scale |
| `--chatty-motion-ease-spring` | `cubic-bezier(0.34, 1.56, 0.64, 1)` | Curve của scale |

#### Variables

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Alias micro | `--chatty-motion-micro` | `var(--chatty-motion-duration-150)` | Same value |
| Alias surface-in | `--chatty-motion-surface-in` | `var(--chatty-motion-duration-350)` | Same value |
| Alias surface-out | `--chatty-motion-surface-out` | `var(--chatty-motion-duration-350)` | Same value |
| Alias sheet-in | `--chatty-motion-sheet-in` | `var(--chatty-motion-duration-400)` | Same value |
| Alias sheet-out | `--chatty-motion-sheet-out` | `var(--chatty-motion-duration-250)` | Same value |
| Easing mặc định | `--ease` | `var(--chatty-motion-ease-out-emphasized)` | Same value |
| Easing panel | `--ease-panel` | `var(--chatty-motion-ease-out-emphasized)` | Same value |
| Spring | `--spring` | `cubic-bezier(0.34, 1.56, 0.64, 1)` | Same value |
| Duration trạng thái | `--dur-1` | `var(--chatty-motion-micro)` | Same value |
| Duration bề mặt | `--dur-2` | `var(--chatty-motion-duration-200)` | Same value |
| Duration vào | `--dur-3` | `var(--chatty-motion-duration-200)` | Same value |
| Duration panel | `--dur-panel` | `var(--chatty-motion-sheet-in)` | Same value |
| Duration tray | `--dur-tray` | `var(--chatty-motion-surface-in)` | Same value |

### Admin

#### Motion durations

| Token | Duration | Use |
| --- | --- | --- |
| `--chatty-motion-duration-50` | Derived(50ms = duration(50)) | Fallback của --p-motion-duration-50 |
| `--chatty-motion-duration-100` | Derived(100ms = duration(100)) | Fallback của --p-motion-duration-100 |
| `--chatty-motion-duration-150` | Derived(150ms = duration(150)) | Fallback của --p-motion-duration-150; Alias --chatty-motion-micro |
| `--chatty-motion-duration-200` | Derived(200ms = duration(200)) | Fallback của --p-motion-duration-200 |
| `--chatty-motion-duration-250` | Derived(250ms = duration(250)) | Fallback của --p-motion-duration-250; Alias --chatty-motion-sheet-out |
| `--chatty-motion-duration-300` | Derived(300ms = duration(300)) | Fallback của --p-motion-duration-300 |
| `--chatty-motion-duration-350` | Derived(350ms = duration(350)) | Fallback của --p-motion-duration-350; Alias --chatty-motion-surface-in và --chatty-motion-surface-out |
| `--chatty-motion-duration-400` | Derived(400ms = duration(400)) | Fallback của --p-motion-duration-400; Alias --chatty-motion-sheet-in |
| `--chatty-motion-duration-450` | Derived(450ms = duration(450)) | Fallback của --p-motion-duration-450 |
| `--chatty-motion-duration-500` | Derived(500ms = duration(500)) | Fallback của --p-motion-duration-500 |

#### Motion easings

| Token | Curve | Use |
| --- | --- | --- |
| `--chatty-motion-ease-standard` | ease | Fallback của biến Polaris --p-motion-ease cùng tên |
| `--chatty-motion-ease-surface` | `cubic-bezier(0.2, 0, 0, 1)` | Giá trị cố định, không đọc Polaris |
| `--chatty-motion-ease-in` | `cubic-bezier(0.42, 0, 1, 1)` | Fallback của biến Polaris --p-motion-ease cùng tên |
| `--chatty-motion-ease-out` | `cubic-bezier(0.19, 0.91, 0.38, 1)` | Fallback của biến Polaris --p-motion-ease cùng tên |
| `--chatty-motion-ease-in-out` | `cubic-bezier(0.42, 0, 0.58, 1)` | Fallback của biến Polaris --p-motion-ease cùng tên |
| `--chatty-motion-ease-out-emphasized` | `cubic-bezier(0.2, 0.8, 0, 1)` | Fallback của biến Polaris --p-motion-ease cùng tên |
| `--chatty-motion-ease-linear` | linear | Fallback của biến Polaris --p-motion-ease cùng tên |
| `--chatty-motion-ease-spring` | `cubic-bezier(0.34, 1.56, 0.64, 1)` | Giá trị cố định, không đọc Polaris |

#### Variables

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Alias micro | `--chatty-motion-micro` | `var(--chatty-motion-duration-150)` | No Dark skin |
| Alias surface-in | `--chatty-motion-surface-in` | `var(--chatty-motion-duration-350)` | No Dark skin |
| Alias surface-out | `--chatty-motion-surface-out` | `var(--chatty-motion-duration-350)` | No Dark skin |
| Alias sheet-in | `--chatty-motion-sheet-in` | `var(--chatty-motion-duration-400)` | No Dark skin |
| Alias sheet-out | `--chatty-motion-sheet-out` | `var(--chatty-motion-duration-250)` | No Dark skin |

## Composed values

| Element | Surface | Light | Dark | Fallback |
| --- | --- | --- | --- | --- |
| Popup mở | Classic | Derived(400ms = duration(400)) với --chatty-motion-ease-out-emphasized | Same value | Không khai báo |
| Popup đóng | Classic | Derived(350ms = duration(350)) với --chatty-motion-ease-out | Same value | Không khai báo |
| Popup opacity | Classic | Derived(250ms = duration(250)) với --chatty-motion-ease-in | Same value | Không khai báo |
| Control hover | AI Mode | Derived(200ms = duration(200)) với --ease; transform 0.18s | Same value | Không khai báo |
| Launcher morph mở / đóng | AI Mode | Derived(400ms = duration(400)) / Derived(350ms = duration(350)) | Same value | Không khai báo |
| Content fade quanh morph | AI Mode | Derived(100ms = duration(100)) cho fade vào và fade ra | Same value | Không khai báo |
| Dòng chờ shimmer | AI Mode | 1500ms linear infinite | Same value | Không khai báo |

### Surface shape change

Đổi nền theo geometry đo thực tế, giữ chữ nguyên kích thước; panel ↔ launcher và detail/bag dùng nhánh timing riêng.

- Sequence: AI Mode từ launcher: morph 400ms rồi content fade-in 100ms; đóng: content fade-out 100ms rồi morph 350ms. Detail/bag nới panel 350ms hai chiều; sidebar opacity vào 200ms sau 100ms, ra 100ms ngay từ đầu. Tất cả endpoint đo runtime; clock bắt đầu sau khi sidebar đã render ở opacity 0. Open thêm 100ms sau morph và close thêm 100ms trước morph còn lệch clock chuẩn; chưa xác nhận giới hạn bước hình học bằng frame trace. Nhánh elementSelector dùng 300ms (:497), không thay duration 350ms detail/bag.
- Standard: AI Mode launcher morph 400/350ms cubic-bezier(.2,0,0,1), delay hình học 0; không cộng fade thêm vào chuẩn. Detail/bag 350ms; giữ composer cùng lớp nền, không reflow chữ. Sidebar trượt riêng (không morph) default 300/200ms; alias hiện 350/350ms là gap. Classic popup chuẩn mở 400ms emphasized-out / tự đóng 250ms in; user exit: nội dung 80–100ms trước surface 200ms out.
- Geometry: surfaceMorph.js:18 đo left/top/width/height bằng getBoundingClientRect và borderRadius/borderColor/backgroundColor/boxShadow bằng computed style. useSurfaceMorph.js:14,80,176 chọn launcher/panel endpoints; không tự đặt scale(0.2) hay origin. Detail/bag dùng width/transform; không thêm scale chữ.
- Text and frame limits: Khi line breaks thay đổi (chuẩn vùng 900–1281px), chữ fade-out 100ms, đổi width khi đã ẩn rồi fade-in 150ms sau mốc 200ms. Code :379 xét actual reflow. Giữ hover trong thread; ba replay không có bước hình học >20% lặp lại, chỉ một bước ≤22% trong một replay được chấp nhận.
- Reduced motion: AI Mode open/close hiện chỉ fade opacity trong 150ms, không đổi geometry. Mở dùng --chatty-motion-ease-out = cubic-bezier(.19,.91,.38,1); đóng dùng --chatty-motion-ease-in = cubic-bezier(.42,0,1,1). Nếu token của nhánh đó không có giá trị, code dùng linear. Resize detail/bag là nhánh khác: fade 150ms linear. Chuẩn cả hai chiều là fade tại chỗ ≤200ms ease-out; curve đóng và resize hiện còn gap.
- Classic observed: PopupBody.scss:184–193 mở bằng sheet-in 400ms emphasized-out, đóng bằng surface-out 350ms out (gap). Keyframes :1813–1835 opacity + translateY ±24px/scale(.97). Reduced :1741–1749 opacity-only 150ms; open native ease-out, close token out.

No complete replay: Geometry, text reflow and interruption require the real consumer, so these branch tracks are a static diagram.

| Element | Property | From | To | Duration | Delay | Easing |
| --- | --- | --- | --- | --- | --- | --- |
| Morph geometry opening | width | Launcher bounds | Panel bounds | 400 ms | after open requested + 0 ms | cubic-bezier(0.2, 0, 0, 1) |
| Morph geometry closing | width | Panel bounds | Launcher bounds | 350 ms | after close content fade completes + 0 ms | cubic-bezier(0.2, 0, 0, 1) |
| Open content | opacity | 0 | 1 | 100 ms | after open morph completes + 0 ms | cubic-bezier(0.19, 0.91, 0.38, 1) |
| Close content | opacity | 1 | 0 | 100 ms | after close requested + 0 ms | cubic-bezier(0.42, 0, 1, 1) |
| Sidebar opening | opacity | 0 | 1 | 200 ms | after sidebar opens + 100 ms | linear |
| Sidebar closing | opacity | 1 | 0 | 100 ms | after sidebar closes + 0 ms | linear |
| Reflow text outgoing | opacity | 1 | 0 | 100 ms | after reflow starts + 0 ms | linear |
| Reflow text incoming | opacity | 0 | 1 | 150 ms | after reflow starts + 200 ms | linear |

Observed:;;;;;; ;  chatty-classic-open · AI Mode; Classic popup comparison · 2026-11-12

### Send and thread anchor

Bubble mới hiện trước waiting; thread tới anchor, wheel/touch huỷ cuộn ngay.

- Sequence: Một clock gửi tin: bubble opacity/translateY 180ms; scroll 350ms; waiting fade duration 150ms, bắt đầu t=180ms sau send (không phải delay 150ms). Nếu waiting mount muộn, tiếp tục phần thời gian còn lại từ send clock.
- Standard: Bubble ease-out, scroll surface (.2,0,0,1); waiting target ease-out nhưng code WAAPI không truyền easing nên linear.
- Anchor: Top là số hoặc function được đo lại. Clamp vào scrollHeight − clientHeight; nếu xa hơn 1 viewport, nhảy tới cách đích 1 viewport trước khi scroll. Giữ keys optimistic → confirmed để không replay bubble đã thấy.
- Reduced motion: Bubble chỉ fade 150ms, không translate; scroll đến anchor ngay. ThinkingIndicator dùng sendDuration 150ms của clock nên waiting không bị ép giữ delay 180ms.
- Avoid: Không kéo người đang đọc phía trên xuống theo từng token; wheel/touchmove huỷ scroll.

No complete replay: A faithful replay needs the real scroll viewport, message key, send clock and interruptible anchor measurements.

| Element | Property | From | To | Duration | Delay | Easing |
| --- | --- | --- | --- | --- | --- | --- |
| Sent bubble | opacity | 0 | 1 | 180 ms | 0 ms | cubic-bezier(0.19, 0.91, 0.38, 1) |
| Sent bubble | transform | translateY(8px) | none | 180 ms | 0 ms | cubic-bezier(0.19, 0.91, 0.38, 1) |
| Waiting line | opacity | 0 | 1 | 150 ms | after send clock starts + 180 ms | linear |

Observed: ;  · Shared chat thread; consumer-owned scroll viewport · 2026-11-12

### Conditional entry and exit

Giữ row trong DOM tới khi fade-out kết thúc; row đang rời không nhận focus.

- Observed: Presence mounts directly with no entry fade; exit opacity 1→0 in 150ms native ease-out, fill both. element.inert=true during exit; setPresent(false) only at animation.onfinish. No animate support: remove immediately.
- Standard: New content fade 150–250ms out; system exit 150–250ms in; skeleton giữ kích thước cuối, CLS ≤0.1. Native ease-out exit và thiếu entry fade là gap.
- Use when: Hiện/ẩn nội dung điều kiện. Không unmount theo timer đoán bằng duration; cancellation phải gỡ callback và trả inert.
- Reduced motion: Chuẩn fade tại chỗ ≤200ms. Presence không có nhánh media-query riêng; observed exit 150ms opacity-only vẫn trong giới hạn.

No complete replay: The property diagram cannot replay React mounting, focus/inert, animation completion and cancellation lifecycle.

| Element | Property | From | To | Duration | Delay | Easing |
| --- | --- | --- | --- | --- | --- | --- |
| New row | display | none | contents | 0 ms | after show becomes true + 0 ms | linear |
| Exiting row | opacity | 1 | 0 | 150 ms | 0 ms | ease-out |
| Exiting row | display | contents | none | 0 ms | after exit animation finishes + 0 ms | linear |

Observed:  · Shared Presence primitive · 2026-11-12


### Waiting status handover

Đổ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

### Page or tab swap

Đổi page đã sẵn sàng trong một frame ở opacity 1; chỉ nội dung sidebar dùng fade-through.

- Sequence: PageView giữ visited pages mounted/hidden, chờ ReadyPage requestAnimationFrame + connected marker rồi onReady. Page chính đổi display/active 0ms, không opacity dip hay empty frame.
- Sidebar: useFadeThrough fade-out 100ms native ease-in, swap at onfinish, CSS incoming fade-in 200ms native ease-out. No frame shows both. With no animatable element, fallback timer 100ms before swap.
- Standard: Page/tab duration 0, opacity 1; đổi geometry cùng frame, không page swap khi surface còn morph. Sidebar out 100ms token in rồi in 200ms token out; native CSS curves còn gap về token.
- Reduced motion: PageView finishes legacy chatty-fade descendants on activation (:48–51); page swap vẫn 0ms. useFadeThrough/fadeThrough.scss không có nhánh reduce riêng.

No complete replay: Readiness, retained React pages and same-frame geometry cannot be proved by a generic property player.

| Element | Property | From | To | Duration | Delay | Easing |
| --- | --- | --- | --- | --- | --- | --- |
| Old main page | display | contents | none | 0 ms | after requested page ready + 0 ms | linear |
| Ready main page | display | none | contents | 0 ms | after requested page ready + 0 ms | linear |
| Sidebar old content | opacity | 1 | 0 | 100 ms | 0 ms | ease-in |
| Sidebar new content | opacity | 0 | 1 | 200 ms | after sidebar old-content fade finishes + 0 ms | ease-out |

Observed:;;  · Shared PageView; AI Mode sidebar content · 2026-11-12


### Add-to-cart chain

Sau server OK: check/flight → badge khi landing → giữ≥800ms → đổi view nếu khách chưa thao tác.

- Sequence: Không bắt đầu check/flight trước server OK. Flight resolves khi hạ cánh; badge cập nhật/bump khi landing. afterCartFeedback nhận landing Promise, đợi 800ms rồi swap; pointerdown/keydown huỷ. Missing image/bag, reduced motion hoặc giới hạn ghost: no flight, promise có thể resolve ngay.
- Standard: Target dùng layout check-only của source: label gốc giữ chỗ nhưng ẩn bằng opacity 0; check 20×20px nằm giữa wrapper, không đặt chữ Added nhìn thấy cạnh check. Added chỉ ở role=status ẩn cho trình đọc màn hình. Giữ check 2s rồi trở về label; source hiện giữ 1650ms là gap duration. Spring feedback ≤350ms; badge 320ms đạt giới hạn. AI Mode system receipt riêng; inbox không CTA; Classic không receipt. CartConfirmation không tự điều phối flight hoặc swap. Giá trị/source hình ảnh nằm trên Add to cart.
- Flight: Clone ảnh tối đa 80px giữ tỉ lệ, tâm ảnh→tâm bag hit-testable. Duration=clamp(round(580×distance/400),300,720)ms; X linear, Y cubic-bezier(.55,0,1,.45). Khoảng cách<120px thì fade tại chỗ 300ms, scale 1→.3. Full visual evidence ở Add to cart. Y/scale at offsets 0/.5/.8/1: (0,1)/(.5dy,.55)/(.8dy,.28)/(dy,.15); opacity 1/.9/.6/0. Badge scale 1/1.35/.92/1.06/1. Source flyToCart.js:31–36,231–238.
- Landing: Badge scales 1/1.35/.92/1.06/1 trong 320ms spring(.34,1.56,.64,1). Bag wiggle 500ms native ease-in-out; +1 rise 28px trong 700ms native ease-out.
- Reduced motion: flyToCart/bumpBadge bỏ flight/bump nên không wiggle/+1. Check hiện ngay, không draw/entry animation; label vẫn transition opacity 150ms. Giữ announcement, count và thứ tự; no-flight landing không chặn server.
- Evidence scope: Các hàng tĩnh ghi opacity envelope của flight 300–720ms; geometry và keyframes nằm ở Flight/Landing. Check row ghi literal ease là fallback Classic của --ease; giá trị inherited thực tế phụ thuộc surface. Classic ProductCard gọi hook useAddToCart → flyToCart; header dùng useLandingCount rồi bumpBadge khi count tăng.

No complete replay: Server success, measured flight geometry, landing and user cancellation cannot be replaced by a fixed global timeline.

| Element | Property | From | To | Duration | Delay | Easing |
| --- | --- | --- | --- | --- | --- | --- |
| Action label | opacity | 1 | 0 | 150 ms | after server confirms add + 0 ms | ease |
| Check | opacity | 0 | 1 | 150 ms | after server confirms add + 0 ms | ease |
| Check polyline | stroke-dashoffset | 24 | 0 | 300 ms | after server confirms add + 0 ms | ease |
| Check | display | grid | none | 0 ms | after added becomes true + 1650 ms | linear |
| Flight image | opacity | 1 | 0 | 300–720 ms | after flight starts + 0 ms | cubic-bezier(0.55, 0, 1, 0.45) |
| View | opacity | 1 | 1 | 0 ms | after landing Promise resolves unless user cancels + 800 ms | linear |

Observed:;;;;;  · AI Mode / Classic; inbox receipt is read-only · 2026-11-12

### Admin thread switch

Đổi hội thoại không animate surface; chuẩn giữ thread cũ đến khi mới ready, skeleton sau 300ms.

- Observed: Hook dùng ensureThread(paramId) và state của paramId của conversation mới. Nhánh adapterLoading trả LoadingSkeleton ngay; không có delay 300ms tại consumer này. Không chứng minh giữ thread cũ khi dữ liệu mới chưa sẵn sàng.
- Standard: Surface 0ms; giữ dữ liệu cũ đến thread mới ready; chỉ hiện skeleton nếu vẫn chờ sau 300ms. Đây là target chưa được chứng minh ở source.
- Use when: Chọn hội thoại liên tục hoặc bằng keyboard; metadata body-small. Không animate surface mỗi lần chọn.
- Reduced motion: Surface vẫn 0ms; không thêm fade. Không có standalone shared component/fixture thể hiện data lifecycle.

No complete replay: The generic player has no real admin route, store or thread-readiness lifecycle to prove this switch.

| Element | Property | From | To | Duration | Delay | Easing |
| --- | --- | --- | --- | --- | --- | --- |
| Thread surface | opacity | 1 | 1 | 0 ms | after route paramId changes + 0 ms | linear |
| Loading skeleton | visibility | hidden | visible | 0 ms | after adapterLoading branch renders + 0 ms | linear |

Observed: ;  · Admin inbox · 2026-11-12

## Copy-paste export

### Classic

```css
.Avada-Faqs_Popup {
  --chatty-motion-duration-50: 50ms;
  --chatty-motion-duration-100: 100ms;
  --chatty-motion-duration-150: 150ms;
  --chatty-motion-duration-200: 200ms;
  --chatty-motion-duration-250: 250ms;
  --chatty-motion-duration-300: 300ms;
  --chatty-motion-duration-350: 350ms;
  --chatty-motion-duration-400: 400ms;
  --chatty-motion-duration-450: 450ms;
  --chatty-motion-duration-500: 500ms;
  --chatty-motion-ease-standard: ease;
  --chatty-motion-ease-surface: cubic-bezier(0.2, 0, 0, 1);
  --chatty-motion-ease-in: cubic-bezier(0.42, 0, 1, 1);
  --chatty-motion-ease-out: cubic-bezier(0.19, 0.91, 0.38, 1);
  --chatty-motion-ease-in-out: cubic-bezier(0.42, 0, 0.58, 1);
  --chatty-motion-ease-out-emphasized: cubic-bezier(0.2, 0.8, 0, 1);
  --chatty-motion-ease-linear: linear;
  --chatty-motion-ease-spring: cubic-bezier(0.34, 1.56, 0.64, 1);
  --chatty-motion-micro: var(--chatty-motion-duration-150);
  --chatty-motion-surface-in: var(--chatty-motion-duration-350);
  --chatty-motion-surface-out: var(--chatty-motion-duration-350);
  --chatty-motion-sheet-in: var(--chatty-motion-duration-400);
  --chatty-motion-sheet-out: var(--chatty-motion-duration-250);
}
```

### AI Mode

```css
.chatty-ai-mode {
  --chatty-motion-duration-50: 50ms;
  --chatty-motion-duration-100: 100ms;
  --chatty-motion-duration-150: 150ms;
  --chatty-motion-duration-200: 200ms;
  --chatty-motion-duration-250: 250ms;
  --chatty-motion-duration-300: 300ms;
  --chatty-motion-duration-350: 350ms;
  --chatty-motion-duration-400: 400ms;
  --chatty-motion-duration-450: 450ms;
  --chatty-motion-duration-500: 500ms;
  --chatty-motion-ease-standard: ease;
  --chatty-motion-ease-surface: cubic-bezier(0.2, 0, 0, 1);
  --chatty-motion-ease-in: cubic-bezier(0.42, 0, 1, 1);
  --chatty-motion-ease-out: cubic-bezier(0.19, 0.91, 0.38, 1);
  --chatty-motion-ease-in-out: cubic-bezier(0.42, 0, 0.58, 1);
  --chatty-motion-ease-out-emphasized: cubic-bezier(0.2, 0.8, 0, 1);
  --chatty-motion-ease-linear: linear;
  --chatty-motion-ease-spring: cubic-bezier(0.34, 1.56, 0.64, 1);
  --chatty-motion-micro: var(--chatty-motion-duration-150);
  --chatty-motion-surface-in: var(--chatty-motion-duration-350);
  --chatty-motion-surface-out: var(--chatty-motion-duration-350);
  --chatty-motion-sheet-in: var(--chatty-motion-duration-400);
  --chatty-motion-sheet-out: var(--chatty-motion-duration-250);
}
.chatty-ai-mode {
  --ease: var(--chatty-motion-ease-out-emphasized);
  --ease-panel: var(--chatty-motion-ease-out-emphasized);
  --spring: cubic-bezier(0.34, 1.56, 0.64, 1);
  --dur-1: var(--chatty-motion-micro);
  --dur-2: var(--chatty-motion-duration-200);
  --dur-3: var(--chatty-motion-duration-200);
  --dur-panel: var(--chatty-motion-sheet-in);
  --dur-tray: var(--chatty-motion-surface-in);
}
```

### Admin

```css
.inbox-v2 {
  --chatty-motion-duration-50: var(--p-motion-duration-50, 50ms);
  --chatty-motion-duration-100: var(--p-motion-duration-100, 100ms);
  --chatty-motion-duration-150: var(--p-motion-duration-150, 150ms);
  --chatty-motion-duration-200: var(--p-motion-duration-200, 200ms);
  --chatty-motion-duration-250: var(--p-motion-duration-250, 250ms);
  --chatty-motion-duration-300: var(--p-motion-duration-300, 300ms);
  --chatty-motion-duration-350: var(--p-motion-duration-350, 350ms);
  --chatty-motion-duration-400: var(--p-motion-duration-400, 400ms);
  --chatty-motion-duration-450: var(--p-motion-duration-450, 450ms);
  --chatty-motion-duration-500: var(--p-motion-duration-500, 500ms);
  --chatty-motion-ease-standard: var(--p-motion-ease-standard, ease);
  --chatty-motion-ease-surface: cubic-bezier(0.2, 0, 0, 1);
  --chatty-motion-ease-in: var(--p-motion-ease-in, cubic-bezier(0.42, 0, 1, 1));
  --chatty-motion-ease-out: var(--p-motion-ease-out, cubic-bezier(0.19, 0.91, 0.38, 1));
  --chatty-motion-ease-in-out: var(--p-motion-ease-in-out, cubic-bezier(0.42, 0, 0.58, 1));
  --chatty-motion-ease-out-emphasized: var(
    --p-motion-ease-out-emphasized,
    cubic-bezier(0.2, 0.8, 0, 1)
  );
  --chatty-motion-ease-linear: var(--p-motion-ease-linear, linear);
  --chatty-motion-ease-spring: cubic-bezier(0.34, 1.56, 0.64, 1);
  --chatty-motion-micro: var(--chatty-motion-duration-150);
  --chatty-motion-surface-in: var(--chatty-motion-duration-350);
  --chatty-motion-surface-out: var(--chatty-motion-duration-350);
  --chatty-motion-sheet-in: var(--chatty-motion-duration-400);
  --chatty-motion-sheet-out: var(--chatty-motion-duration-250);
}
```

## Contrast matrix

| Surface | Pair | Light ratio | Dark ratio |
| --- | --- | --- | --- |
| Classic | Không áp dụng: token motion không đặt màu | Not available | Not available |
| AI Mode | Không áp dụng: token motion không đặt màu | Not available | Not available |
| Admin | Không áp dụng: token motion không đặt màu | Not available | No Dark skin |

## Target

```target
| Surface | Now | Target |
| --- | --- | --- |
| Classic · AI Mode | Panel resize: code hiện tại vẫn vi phạm, ghi width theo từng frame và dịch layout box. Layout shift mỗi lần: bag AI Mode desktop 0.29–0.44; Classic Expand/Collapse 0.073–0.080. CLS báo 0 ở 23/24 lần vì shift nằm trong cửa sổ 500 mili-giây sau input; đuôi morph tới 556 mili-giây đã rò vào CLS một lần (0.0013). CLS báo 0 không có nghĩa là không dịch. Mobile không có resize morph. AI Mode product detail chưa kiểm, không suy số đo bag sang detail. | Not in code yet — build with the body values. Resize chỉ animate clip-path/transform trên layout box cố định và xong hẳn trong 500 mili-giây sau input; đích tối đa 300 mili-giây kể cả đuôi, giữ curve surface. Đo lại cả đuôi trên thiết bị chậm trước khi ghi là tuân thủ. |
| AI Mode | Source comment says keep in sync with const/motion.js, but that file is not in the checkout. | Not in code yet — build with the body values. Remove the stale comment or point it at the real owner file. |
```

Example — Current code còn dịch layout box dù CLS thường báo 0; Target dùng clip-path/transform, đích tối đa 300 mili-giây kể cả đuôi.

```jsx
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 PanelResize() {
  return <Diagram id="panel-resize"><SurfaceComparison resize /></Diagram>;
}
```

