On this page

Motion

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

Copy page as MarkdownRead Markdown ↗

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.
On this page

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

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.

Show code
motion-rules.jsxWrap code linesCopy
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 50msDerived(50ms = duration(50)) Bước của scale
--chatty-motion-duration-100 100msDerived(100ms = duration(100)) Bước của scale
--chatty-motion-duration-150 150msDerived(150ms = duration(150)) Bước của scale; Alias --chatty-motion-micro
--chatty-motion-duration-200 200msDerived(200ms = duration(200)) Bước của scale
--chatty-motion-duration-250 250msDerived(250ms = duration(250)) Bước của scale; Alias --chatty-motion-sheet-out
--chatty-motion-duration-300 300msDerived(300ms = duration(300)) Bước của scale
--chatty-motion-duration-350 350msDerived(350ms = duration(350)) Bước của scale; Alias --chatty-motion-surface-in và --chatty-motion-surface-out
--chatty-motion-duration-400 400msDerived(400ms = duration(400)) Bước của scale; Alias --chatty-motion-sheet-in
--chatty-motion-duration-450 450msDerived(450ms = duration(450)) Bước của scale
--chatty-motion-duration-500 500msDerived(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 50msDerived(50ms = duration(50)) Bước của scale
--chatty-motion-duration-100 100msDerived(100ms = duration(100)) Bước của scale
--chatty-motion-duration-150 150msDerived(150ms = duration(150)) Bước của scale; Alias --chatty-motion-micro
--chatty-motion-duration-200 200msDerived(200ms = duration(200)) Bước của scale
--chatty-motion-duration-250 250msDerived(250ms = duration(250)) Bước của scale; Alias --chatty-motion-sheet-out
--chatty-motion-duration-300 300msDerived(300ms = duration(300)) Bước của scale
--chatty-motion-duration-350 350msDerived(350ms = duration(350)) Bước của scale; Alias --chatty-motion-surface-in và --chatty-motion-surface-out
--chatty-motion-duration-400 400msDerived(400ms = duration(400)) Bước của scale; Alias --chatty-motion-sheet-in
--chatty-motion-duration-450 450msDerived(450ms = duration(450)) Bước của scale
--chatty-motion-duration-500 500msDerived(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 50msDerived(50ms = duration(50)) Fallback của --p-motion-duration-50
--chatty-motion-duration-100 100msDerived(100ms = duration(100)) Fallback của --p-motion-duration-100
--chatty-motion-duration-150 150msDerived(150ms = duration(150)) Fallback của --p-motion-duration-150; Alias --chatty-motion-micro
--chatty-motion-duration-200 200msDerived(200ms = duration(200)) Fallback của --p-motion-duration-200
--chatty-motion-duration-250 250msDerived(250ms = duration(250)) Fallback của --p-motion-duration-250; Alias --chatty-motion-sheet-out
--chatty-motion-duration-300 300msDerived(300ms = duration(300)) Fallback của --p-motion-duration-300
--chatty-motion-duration-350 350msDerived(350ms = duration(350)) Fallback của --p-motion-duration-350; Alias --chatty-motion-surface-in và --chatty-motion-surface-out
--chatty-motion-duration-400 400msDerived(400ms = duration(400)) Fallback của --p-motion-duration-400; Alias --chatty-motion-sheet-in
--chatty-motion-duration-450 450msDerived(450ms = duration(450)) Fallback của --p-motion-duration-450
--chatty-motion-duration-500 500msDerived(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 400msDerived(400ms = duration(400)) với --chatty-motion-ease-out-emphasized Same value Không khai báo
Popup đóng Classic 350msDerived(350ms = duration(350)) với --chatty-motion-ease-out Same value Không khai báo
Popup opacity Classic 250msDerived(250ms = duration(250)) với --chatty-motion-ease-in Same value Không khai báo
Control hover AI Mode 200msDerived(200ms = duration(200)) với --ease; transform 0.18s Same value Không khai báo
Launcher morph mở / đóng AI Mode 400msDerived(400ms = duration(400)) / 350msDerived(350ms = duration(350)) Same value Không khai báo
Content fade quanh morph AI Mode 100msDerived(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

AI Mode · Motion example

Show code
useSurfaceMorph.js; surfaceMorph.jsWrap code linesCopy
/**
 * Morph one empty material between measured endpoints without resizing or scaling the thread.
 * @param {Object} rootRef
 * @param {Object} options focus/readiness state or a resizeKey/expanded pair with a contentSelector
 */
export function useSurfaceMorph(rootRef, options) {
  const {isFocused, ready, resizeKey} = options;
  useResizeMorph(rootRef, options);
  const previous = useRef({focused: false});
  const active = useRef(null);
  const pinnedStyle = useRef(null);

  useLayoutEffect(() => {
    if (resizeKey !== undefined) return;
    const root = rootRef.current;
    const bar = root?.querySelector('.aimode-sbar-container');
    const panel = root?.querySelector('.aimode-panel');
    if (!root) return;
    const before = previous.current;
    if (bar && launcherFrame(root, bar)) before.launcher = bar;
    if (!bar && !before.closed) return;
    if (!ready || !panel || !before.closed) {
      if (!isFocused) before.closed = (bar && launcherFrame(root, bar)) || before.closed;
      if (!ready || !panel) return;
      if (!before.closed) {
        before.focused = isFocused;
        before.open = readMorphFrame(panel);
        return;
      }
    }
    if (before.focused === isFocused) {
      if (!active.current) {
        if (isFocused) before.open = readMorphFrame(panel);
        else before.closed = (bar && launcherFrame(root, bar)) || before.closed;
      }
      return;
    }
    const running = active.current;
    const current = running
      ? running.surface && running.host.style.display !== 'none'
        ? running.readFrame()
        : before.open
      : null;
    running?.animations.forEach(animation => animation.cancel());
    running?.host?.remove();
    if (pinnedStyle.current !== null) {
      panel.style.cssText = pinnedStyle.current;
      pinnedStyle.current = null;
    }
    const split = panel.querySelector('.aimode-panel-split');
    const scroll = panel.querySelector('.chatty-chat-viewport');
    if (isFocused) {
      before.open = readMorphFrame(panel);
      if (scroll && before.scrollTop !== undefined) scroll.scrollTop = before.scrollTop;
    } else {
      before.closed = (bar && launcherFrame(root, bar)) || before.closed;
      // Keep the departing content at its full open geometry, including mobile's composer gutter.
      pinnedStyle.current = panel.style.cssText;
      const rootRect = root.getBoundingClientRect();
      const scaleX = root.offsetWidth ? rootRect.width / root.offsetWidth : 1;
      const scaleY = root.offsetHeight ? rootRect.height / root.offsetHeight : 1;
      Object.assign(panel.style, {
        left: `${(parseFloat(before.open.left) - rootRect.left) / scaleX}px`,
        top: `${(parseFloat(before.open.top) - rootRect.top) / scaleY}px`,
        position: 'absolute',
        bottom: 'auto',
        width: `${parseFloat(before.open.width) / scaleX}px`,
        height: `${parseFloat(before.open.height) / scaleY}px`,
        maxHeight: 'none',
        paddingBottom: before.paddingBottom || '0px',
        transform: 'none'
      });
    }
    before.focused = isFocused;
    const style = getComputedStyle(root);
    const duration = readMotionDuration({
      style,
      token: isFocused ? '--chatty-motion-duration-400' : '--chatty-motion-duration-350',
      fallback: isFocused ? 400 : 350
    });
    const easing =
      style.getPropertyValue('--chatty-motion-ease-surface').trim() || 'cubic-bezier(0.2, 0, 0, 1)';
    const fadeIn = readMotionDuration({
      style,
      token: '--chatty-motion-duration-100',
      fallback: 100
    });
    const fadeOut = readMotionDuration({
      style,
      token: '--chatty-motion-duration-100',
      fallback: 100
    });
    const reducedDuration = readMotionDuration({
      style,
      token: '--chatty-motion-micro',
      fallback: 150
    });
    const motion = {animations: [], host: null, surface: null};
    active.current = motion;
    const fade = ({element, from, to, duration, finish}) => {
      if (!element?.animate) return finish();
      const animation = element.animate([{opacity: from}, {opacity: to}], {
        duration,
        easing:
          style
            .getPropertyValue(to ? '--chatty-motion-ease-out' : '--chatty-motion-ease-in')
            .trim() || 'linear',
        fill: 'both'
      });
      motion.animations.push(animation);
      animation.onfinish = finish;
    };
    const complete = () => {
      motion.host?.remove();
      delete root.dataset.panelMorph;
      motion.animations.forEach(animation => animation.cancel());
      active.current = null;
      if (!isFocused) panel.dispatchEvent(new CustomEvent('chatty:surface-morph-end'));
      if (isFocused) {
        before.open = readMorphFrame(panel);
        before.paddingBottom = getComputedStyle(panel).paddingBottom;
      }
    };
    if (!panel.animate || window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      fade({
        element: panel,
        from: isFocused ? 0 : 1,
        to: isFocused ? 1 : 0,
        duration: reducedDuration,
        finish: complete
      });
      return;
    }
    const morph = () => {
      root.dataset.panelMorph = 'shape';
      const host = document.createElement('div');
      host.className = 'chatty-ai-mode aimode-panel-morph-host';
      host.dataset.theme = root.dataset.theme || 'dark';
      host.setAttribute('aria-hidden', 'true');
      for (const name of Array.from(style)) {
        if (name.startsWith('--')) host.style.setProperty(name, style.getPropertyValue(name));
      }
      const shadow = document.createElement('div');
      shadow.className = 'aimode-panel-morph-shadow';
      const shadowFill = document.createElement('div');
      shadowFill.className = 'aimode-panel-morph-shadow-fill';
      shadow.append(shadowFill);
      const edge = document.createElement('div');
      edge.className = 'aimode-panel-morph-edge';
      const surface = document.createElement('div');
      surface.className = 'chatty-glass-regular aimode-panel-morph';
      host.append(shadow, edge, surface);
      document.body.append(host);
      motion.host = host;
      motion.surface = surface;
      const from = current || (isFocused ? before.closed : before.open);
      const to = isFocused ? before.open : before.closed;
      host.classList.toggle('chatty-lg-refract', root.classList.contains('chatty-lg-refract'));
      const label =
        !isFocused &&
        (root.querySelector('.aimode-sbar-container') || before.launcher)?.cloneNode(true);
      if (label) {
        label.classList.add('aimode-panel-morph-label');
        label.inert = true;
        label.querySelectorAll('[id]').forEach(node => node.removeAttribute('id'));
        Object.assign(label.style, {
          position: 'absolute',
          width: to.width,
          height: to.height,
          top: `${Math.max(0, parseFloat(to.top) - parseFloat(from.top))}px`,
          left: `${Math.max(0, parseFloat(to.left) - parseFloat(from.left))}px`,
          transform: 'none',
          transition: 'none',
          opacity: '0'
        });
        host.classList.add('state-resting');
        if (root.classList.contains('is-compact')) host.classList.add('is-compact');
        if (root.classList.contains('has-bag')) host.classList.add('has-bag');
        surface.append(label);
      }
      const animation = morphClippedSurface({
        element: surface,
        layers: [{element: edge, outset: 1}, {element: shadowFill}],
        from,
        to,
        timing: {duration, easing},
        onStart: () => {
          host.classList.toggle('chatty-lg-refract', root.classList.contains('chatty-lg-refract'));
          if (!label) return;
          const reveal = label.animate([{opacity: 0}, {opacity: 1}], {
            duration: fadeIn,
            delay: duration - fadeIn,
            easing: style.getPropertyValue('--chatty-motion-ease-out').trim() || 'linear',
            fill: 'both'
          });
          motion.animations.push(reveal);
        },
        onFinish: () => {
          if (!isFocused) return complete();
          host.style.display = 'none';
          root.dataset.panelMorph = 'content';
          const dock = root.querySelector('.aimode-sbar-dock');
          fade({element: dock, from: 0, to: 1, duration: fadeIn, finish: () => {}});
          fade({element: split, from: 0, to: 1, duration: fadeIn, finish: complete});
        }
      });
      motion.readFrame = animation.readFrame;
      motion.animations.push(animation);
    };
    if (isFocused || running) morph();
    else {
      root.dataset.panelMorph = 'out';
      fade({element: split, from: 1, to: 0, duration: fadeOut, finish: morph});
    }
  });

  useLayoutEffect(() => {
    if (resizeKey !== undefined) return;
    const root = rootRef.current;
    const panel = root?.querySelector('.aimode-panel');
    const bar = root?.querySelector('.aimode-sbar-container');
    const rememberScroll = event => {
      if (
        previous.current.focused &&
        !active.current &&
        event.target.matches?.('.chatty-chat-viewport')
      )
        previous.current.scrollTop = event.target.scrollTop;
    };
    const rememberLauncher = () => {
      if (!previous.current.focused && !active.current && bar)
        previous.current.closed = launcherFrame(root, bar) || previous.current.closed;
    };
    root?.addEventListener('scroll', rememberScroll, true);
    root?.addEventListener('pointerdown', rememberLauncher, true);
    root?.addEventListener('keydown', rememberLauncher, true);
    const rememberFrame = () => {
      if (active.current) return;
      if (previous.current.focused && panel) {
        previous.current.open = readMorphFrame(panel);
        previous.current.paddingBottom = getComputedStyle(panel).paddingBottom;
      } else if (bar) previous.current.closed = launcherFrame(root, bar) || previous.current.closed;
    };
    // A viewport resize can move a fixed-width surface without notifying ResizeObserver.
    window.addEventListener('resize', rememberFrame);
    const observer =
      typeof ResizeObserver === 'function' ? new ResizeObserver(rememberFrame) : null;
    if (panel) observer?.observe(panel);
    if (bar) observer?.observe(bar);
    return () => {
      observer?.disconnect();
      window.removeEventListener('resize', rememberFrame);
      root?.removeEventListener('scroll', rememberScroll, true);
      root?.removeEventListener('pointerdown', rememberLauncher, true);
      root?.removeEventListener('keydown', rememberLauncher, true);
    };
  });

  useLayoutEffect(
    () => () => {
      active.current?.animations.forEach(animation => animation.cancel());
      active.current?.host?.remove();
      active.current = null;
      const root = rootRef.current;
      if (root) delete root.dataset.panelMorph;
    },
    []
  );
}

/**
 * Paint a surface's starting rectangle, then animate its bounds; cancellation also stops pending paint callbacks.
 * @param {HTMLElement} element
 * @param {Object} from
 * @param {Object} to
 * @param {Object} timing
 * @param {Function} onStart
 * @param {Function} onFrame optional main-thread painter receiving eased progress and elapsed time
 * @param {Function} onFinish
 * @returns {{cancel: Function}}
 */
export function morphSurface({element, from, to, timing, onStart, onFrame, onFinish}) {
  let animation;
  let frame;
  Object.assign(element.style, from);
  // A cold GPU paint must finish before the clock can skip the first intermediate sizes.
  frame = requestAnimationFrame(() => {
    frame = requestAnimationFrame(() => {
      animation = element.animate(onFrame ? [] : [from, to], {...timing, fill: 'both'});
      // The main-thread painter owns time; a pending native clock can catch up between paints.
      if (onFrame) animation.pause();
      const start = performance.now();
      const tick = timestamp => {
        animation.currentTime = Math.max(0, Math.min(timing.duration, timestamp - start));
        const progress = animation.effect.getComputedTiming().progress ?? 0;
        onFrame(progress, Number(animation.currentTime) || 0);
        if (animation.currentTime < timing.duration) frame = requestAnimationFrame(tick);
        else animation.onfinish();
      };
      animation.onfinish = () => {
        if (onFrame) onFrame(1, timing.duration);
        onFinish?.();
      };
      onStart?.();
      if (onFrame) tick(start);
    });
  });
  return {
    cancel() {
      cancelAnimationFrame(frame);
      animation?.cancel();
    }
  };
}

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

Observed · AI Mode; Classic popup comparison

  • Event-relative
  • width + opacity
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.
open requested · 1 property row · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
Morph geometry opening · width
400 ms
close content fade completes · 1 property row · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
Morph geometry closing · width
350 ms
open morph completes · 1 property row · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
Open content · opacity
100 ms
close requested · 1 property row · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
Close content · opacity
100 ms
sidebar opens · 1 property row · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
Sidebar opening · opacity
200 ms
sidebar closes · 1 property row · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
Sidebar closing · opacity
100 ms
reflow starts · 2 property rows · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
Reflow text outgoing · opacity
100 ms
Reflow text incoming · opacity
150 ms

What animates

ElementPropertyFrom / ToDuration / DelayEasing
Morph geometry openingwidthLauncher bounds → Panel bounds400 ms after open requested + 0 mscubic-bezier(0.2, 0, 0, 1)
Morph geometry closingwidthPanel bounds → Launcher bounds350 ms after close content fade completes + 0 mscubic-bezier(0.2, 0, 0, 1)
Open contentopacity0 → 1100 ms after open morph completes + 0 mscubic-bezier(0.19, 0.91, 0.38, 1)
Close contentopacity1 → 0100 ms after close requested + 0 mscubic-bezier(0.42, 0, 1, 1)
Sidebar openingopacity0 → 1200 ms after sidebar opens + 100 mslinear
Sidebar closingopacity1 → 0100 ms after sidebar closes + 0 mslinear
Reflow text outgoingopacity1 → 0100 ms after reflow starts + 0 mslinear
Reflow text incomingopacity0 → 1150 ms after reflow starts + 200 mslinear

Send and thread anchor

AI Mode · Motion example

Show code
sendMotion.js; ThinkingIndicator.jsxWrap code linesCopy
/**
 * Reveal a sent bubble and move its thread on the same interruptible clock.
 * @param {HTMLElement} viewport
 * @param {HTMLElement} bubble
 * @param {number|Function} top target scroll position, remeasured through optimistic handoffs
 * @returns {{cancel: Function}}
 */
export function animateSentTurn({viewport, bubble, top}) {
  moving.get(viewport)?.cancel();
  const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
  const style = getComputedStyle(viewport);
  const easing =
    style.getPropertyValue('--chatty-motion-ease-out').trim() ||
    'cubic-bezier(0.19, 0.91, 0.38, 1)';
  if (bubble && !revealed.has(bubble)) {
    revealed.add(bubble);
    viewport.dataset.chattySendStart = String(performance.now());
    viewport.dataset.chattySendDuration = String(reduced ? 150 : 180);
    viewport.dataset.chattySendKey = bubble.dataset.messageKey || bubble.dataset.messageId || '';
    bubble.animate?.(
      reduced
        ? [{opacity: 0}, {opacity: 1}]
        : [
            {opacity: 0, transform: 'translateY(8px)'},
            {opacity: 1, transform: 'none'}
          ],
      {duration: reduced ? 150 : 180, easing}
    );
  }
  viewport.dispatchEvent(new Event('chatty:send-start'));
  const target = () =>
    Math.max(
      0,
      Math.min(
        typeof top === 'function' ? top() : top,
        viewport.scrollHeight - viewport.clientHeight
      )
    );
  if (reduced || !viewport.animate) {
    viewport.scrollTo({top: target(), behavior: 'auto'});
    return {cancel() {}};
  }
  const start = Math.max(
    target() - viewport.clientHeight,
    Math.min(viewport.scrollTop, target() + viewport.clientHeight)
  );
  viewport.scrollTo({top: start, behavior: 'auto'});
  const clock = viewport.animate([], {
    duration: readMotionDuration({style, token: '--chatty-motion-duration-350', fallback: 350}),
    easing:
      style.getPropertyValue('--chatty-motion-ease-surface').trim() || 'cubic-bezier(0.2, 0, 0, 1)'
  });
  let frame;
  const controller = {
    cancel() {
      if (moving.get(viewport) !== controller) return;
      moving.delete(viewport);
      cancelAnimationFrame(frame);
      clock.cancel();
      viewport.removeEventListener('wheel', controller.cancel);
      viewport.removeEventListener('touchmove', controller.cancel);
    }
  };
  moving.set(viewport, controller);
  viewport.addEventListener('wheel', controller.cancel, {passive: true});
  viewport.addEventListener('touchmove', controller.cancel, {passive: true});
  const tick = () => {
    if (moving.get(viewport) !== controller) return;
    const progress = clock.effect.getComputedTiming().progress ?? 0;
    viewport.scrollTo({top: start + (target() - start) * progress, behavior: 'auto'});
    if (progress >= 1) controller.cancel();
    else frame = requestAnimationFrame(tick);
  };
  clock.onfinish = () => {
    if (moving.get(viewport) !== controller) return;
    viewport.scrollTo({top: target(), behavior: 'auto'});
    controller.cancel();
  };
  frame = requestAnimationFrame(tick);
  return controller;
}

/** Show the current waiting line in the reply slot until the answer takes over.
 * @param {boolean} active
 * @param {string} text translated waiting or merchant label
 * @param {string} sendKey stable client turn for send-relative entry
 */
export function ThinkingIndicator({active = true, text = '', sendKey = ''}) {
  const ref = useRef(null);
  const previous = useRef(text);
  const outgoing = previous.current;
  useLayoutEffect(() => {
    const el = ref.current;
    if (!el) return;
    previous.current = text;
    const animations = [];
    if (outgoing !== text) {
      const old = el.querySelector('.chatty-thinking__previous');
      const current = el.querySelector('.chatty-thinking__label');
      const fade = old?.animate?.([{opacity: 1}, {opacity: 0}], {duration: 150});
      if (fade) {
        fade.onfinish = () => {
          old.hidden = true;
        };
        animations.push(fade);
      }
      const enter = current?.animate?.([{opacity: 0}, {opacity: 1}], {duration: 150});
      if (enter) animations.push(enter);
    }
    return () => animations.forEach(animation => animation.cancel());
  }, [text, active]);
  useLayoutEffect(() => {
    const el = ref.current;
    if (!el) return;
    const viewport = el.closest('.chatty-chat-viewport, .chatty-surface__viewport');
    let animation;
    const enter = () => {
      const matchingClock = !sendKey || viewport?.dataset.chattySendKey === sendKey;
      if (!matchingClock && viewport?.dataset.chattyPendingSendKey === sendKey) return;
      animation?.cancel();
      const duration = Number(viewport?.dataset.chattySendDuration) || 180;
      const hasClock = matchingClock && viewport?.hasAttribute('data-chatty-send-start');
      const previousEntry = viewport && entered.get(viewport);
      const seen = sendKey && previousEntry?.key === sendKey;
      const fadeStart = hasClock
        ? Number(viewport.dataset.chattySendStart) + duration
        : seen
          ? previousEntry.at
          : performance.now();
      const elapsed = performance.now() - fadeStart;
      const progress = seen ? Math.max(0, Math.min(1, elapsed / 150)) : 0;
      el.style.opacity = '';
      if (progress >= 1) return;
      if (viewport && sendKey) entered.set(viewport, {key: sendKey, at: fadeStart});
      animation = el.animate?.([{opacity: progress}, {opacity: 1}], {
        duration: 150 * (1 - progress),
        delay: hasClock ? Math.max(0, -elapsed) : 0,
        fill: 'backwards'
      });
    };
    if (sendKey) el.style.opacity = '0';
    enter();
    viewport?.addEventListener('chatty:send-start', enter);
    return () => {
      animation?.cancel();
      viewport?.removeEventListener('chatty:send-start', enter);
    };
  }, [active, sendKey]);
  if (!active) return null;
  return (
    <span ref={ref} className="chatty-thinking" role="status" aria-live="polite">
      {text ? (
        <span className="chatty-thinking__labels">
          <span className="chatty-thinking__previous" aria-hidden="true" hidden={outgoing === text}>
            {outgoing}
          </span>
          <span className="chatty-thinking__label">{text}</span>
        </span>
      ) : (
        <span className="chatty-thinking__dot" aria-label="…" />
      )}
    </span>
  );
}

Classic · Motion example

Show code
sendMotion.js; ThinkingIndicator.jsxWrap code linesCopy
/**
 * Reveal a sent bubble and move its thread on the same interruptible clock.
 * @param {HTMLElement} viewport
 * @param {HTMLElement} bubble
 * @param {number|Function} top target scroll position, remeasured through optimistic handoffs
 * @returns {{cancel: Function}}
 */
export function animateSentTurn({viewport, bubble, top}) {
  moving.get(viewport)?.cancel();
  const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
  const style = getComputedStyle(viewport);
  const easing =
    style.getPropertyValue('--chatty-motion-ease-out').trim() ||
    'cubic-bezier(0.19, 0.91, 0.38, 1)';
  if (bubble && !revealed.has(bubble)) {
    revealed.add(bubble);
    viewport.dataset.chattySendStart = String(performance.now());
    viewport.dataset.chattySendDuration = String(reduced ? 150 : 180);
    viewport.dataset.chattySendKey = bubble.dataset.messageKey || bubble.dataset.messageId || '';
    bubble.animate?.(
      reduced
        ? [{opacity: 0}, {opacity: 1}]
        : [
            {opacity: 0, transform: 'translateY(8px)'},
            {opacity: 1, transform: 'none'}
          ],
      {duration: reduced ? 150 : 180, easing}
    );
  }
  viewport.dispatchEvent(new Event('chatty:send-start'));
  const target = () =>
    Math.max(
      0,
      Math.min(
        typeof top === 'function' ? top() : top,
        viewport.scrollHeight - viewport.clientHeight
      )
    );
  if (reduced || !viewport.animate) {
    viewport.scrollTo({top: target(), behavior: 'auto'});
    return {cancel() {}};
  }
  const start = Math.max(
    target() - viewport.clientHeight,
    Math.min(viewport.scrollTop, target() + viewport.clientHeight)
  );
  viewport.scrollTo({top: start, behavior: 'auto'});
  const clock = viewport.animate([], {
    duration: readMotionDuration({style, token: '--chatty-motion-duration-350', fallback: 350}),
    easing:
      style.getPropertyValue('--chatty-motion-ease-surface').trim() || 'cubic-bezier(0.2, 0, 0, 1)'
  });
  let frame;
  const controller = {
    cancel() {
      if (moving.get(viewport) !== controller) return;
      moving.delete(viewport);
      cancelAnimationFrame(frame);
      clock.cancel();
      viewport.removeEventListener('wheel', controller.cancel);
      viewport.removeEventListener('touchmove', controller.cancel);
    }
  };
  moving.set(viewport, controller);
  viewport.addEventListener('wheel', controller.cancel, {passive: true});
  viewport.addEventListener('touchmove', controller.cancel, {passive: true});
  const tick = () => {
    if (moving.get(viewport) !== controller) return;
    const progress = clock.effect.getComputedTiming().progress ?? 0;
    viewport.scrollTo({top: start + (target() - start) * progress, behavior: 'auto'});
    if (progress >= 1) controller.cancel();
    else frame = requestAnimationFrame(tick);
  };
  clock.onfinish = () => {
    if (moving.get(viewport) !== controller) return;
    viewport.scrollTo({top: target(), behavior: 'auto'});
    controller.cancel();
  };
  frame = requestAnimationFrame(tick);
  return controller;
}

/** Show the current waiting line in the reply slot until the answer takes over.
 * @param {boolean} active
 * @param {string} text translated waiting or merchant label
 * @param {string} sendKey stable client turn for send-relative entry
 */
export function ThinkingIndicator({active = true, text = '', sendKey = ''}) {
  const ref = useRef(null);
  const previous = useRef(text);
  const outgoing = previous.current;
  useLayoutEffect(() => {
    const el = ref.current;
    if (!el) return;
    previous.current = text;
    const animations = [];
    if (outgoing !== text) {
      const old = el.querySelector('.chatty-thinking__previous');
      const current = el.querySelector('.chatty-thinking__label');
      const fade = old?.animate?.([{opacity: 1}, {opacity: 0}], {duration: 150});
      if (fade) {
        fade.onfinish = () => {
          old.hidden = true;
        };
        animations.push(fade);
      }
      const enter = current?.animate?.([{opacity: 0}, {opacity: 1}], {duration: 150});
      if (enter) animations.push(enter);
    }
    return () => animations.forEach(animation => animation.cancel());
  }, [text, active]);
  useLayoutEffect(() => {
    const el = ref.current;
    if (!el) return;
    const viewport = el.closest('.chatty-chat-viewport, .chatty-surface__viewport');
    let animation;
    const enter = () => {
      const matchingClock = !sendKey || viewport?.dataset.chattySendKey === sendKey;
      if (!matchingClock && viewport?.dataset.chattyPendingSendKey === sendKey) return;
      animation?.cancel();
      const duration = Number(viewport?.dataset.chattySendDuration) || 180;
      const hasClock = matchingClock && viewport?.hasAttribute('data-chatty-send-start');
      const previousEntry = viewport && entered.get(viewport);
      const seen = sendKey && previousEntry?.key === sendKey;
      const fadeStart = hasClock
        ? Number(viewport.dataset.chattySendStart) + duration
        : seen
          ? previousEntry.at
          : performance.now();
      const elapsed = performance.now() - fadeStart;
      const progress = seen ? Math.max(0, Math.min(1, elapsed / 150)) : 0;
      el.style.opacity = '';
      if (progress >= 1) return;
      if (viewport && sendKey) entered.set(viewport, {key: sendKey, at: fadeStart});
      animation = el.animate?.([{opacity: progress}, {opacity: 1}], {
        duration: 150 * (1 - progress),
        delay: hasClock ? Math.max(0, -elapsed) : 0,
        fill: 'backwards'
      });
    };
    if (sendKey) el.style.opacity = '0';
    enter();
    viewport?.addEventListener('chatty:send-start', enter);
    return () => {
      animation?.cancel();
      viewport?.removeEventListener('chatty:send-start', enter);
    };
  }, [active, sendKey]);
  if (!active) return null;
  return (
    <span ref={ref} className="chatty-thinking" role="status" aria-live="polite">
      {text ? (
        <span className="chatty-thinking__labels">
          <span className="chatty-thinking__previous" aria-hidden="true" hidden={outgoing === text}>
            {outgoing}
          </span>
          <span className="chatty-thinking__label">{text}</span>
        </span>
      ) : (
        <span className="chatty-thinking__dot" aria-label="…" />
      )}
    </span>
  );
}

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

Observed · Shared chat thread; consumer-owned scroll viewport

  • Event-relative
  • opacity + transform
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.
Moment start · 2 property rows · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
Sent bubble · opacity
180 ms
Sent bubble · transform
180 ms
send clock starts · 1 property row · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
Waiting line · opacity
150 ms

What animates

ElementPropertyFrom / ToDuration / DelayEasing
Sent bubbleopacity0 → 1180 ms 0 mscubic-bezier(0.19, 0.91, 0.38, 1)
Sent bubbletransformtranslateY(8px) → none180 ms 0 mscubic-bezier(0.19, 0.91, 0.38, 1)
Waiting lineopacity0 → 1150 ms after send clock starts + 180 mslinear

Conditional entry and exit

AI Mode · Motion example

Show code
Presence.jsxWrap code linesCopy
/**
 * Mount on entry before parent layout effects and retain exits until their native fade finishes.
 * @param {boolean} show
 * @param {React.ReactNode} children
 * @param {Object} elementRef optional portaled control ref
 */
export function Presence({show, children, elementRef}) {
  const [present, setPresent] = useState(show);
  const ref = useRef(null);
  const last = useRef(children);
  if (show) last.current = children;
  useLayoutEffect(() => {
    if (show) {
      setPresent(true);
      return;
    }
    const element = elementRef?.current || ref.current?.firstElementChild;
    if (!element) return;
    if (!element.animate) {
      setPresent(false);
      return;
    }
    element.inert = true;
    const animation = element.animate([{opacity: 1}, {opacity: 0}], {
      duration: 150,
      easing: 'ease-out',
      fill: 'both'
    });
    animation.onfinish = () => setPresent(false);
    return () => {
      animation.onfinish = null;
      animation.cancel();
      element.inert = false;
    };
  }, [show, elementRef]);
  return show || present ? (
    <div
      ref={ref}
      style={{display: 'contents'}}
      inert={show ? undefined : ''}
      aria-hidden={show ? undefined : true}
    >
      {last.current}
    </div>
  ) : null;
}

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

Observed · Shared Presence primitive

  • Event-relative
  • display + opacity
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.
show becomes true · 1 property row · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
New row · display
◆
Instant
Moment start · 1 property row · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
Exiting row · opacity
150 ms
exit animation finishes · 1 property row · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
Exiting row · display
◆
Instant

What animates

ElementPropertyFrom / ToDuration / DelayEasing
New rowdisplaynone → contents0 ms after show becomes true + 0 mslinear
Exiting rowopacity1 → 0150 ms 0 msease-out
Exiting rowdisplaycontents → none0 ms after exit animation finishes + 0 mslinear

Waiting status handover

AI Mode · Motion example

Show code
ThinkingIndicator.jsx; Markdown.jsWrap code linesCopy
/** Show the current waiting line in the reply slot until the answer takes over.
 * @param {boolean} active
 * @param {string} text translated waiting or merchant label
 * @param {string} sendKey stable client turn for send-relative entry
 */
export function ThinkingIndicator({active = true, text = '', sendKey = ''}) {
  const ref = useRef(null);
  const previous = useRef(text);
  const outgoing = previous.current;
  useLayoutEffect(() => {
    const el = ref.current;
    if (!el) return;
    previous.current = text;
    const animations = [];
    if (outgoing !== text) {
      const old = el.querySelector('.chatty-thinking__previous');
      const current = el.querySelector('.chatty-thinking__label');
      const fade = old?.animate?.([{opacity: 1}, {opacity: 0}], {duration: 150});
      if (fade) {
        fade.onfinish = () => {
          old.hidden = true;
        };
        animations.push(fade);
      }
      const enter = current?.animate?.([{opacity: 0}, {opacity: 1}], {duration: 150});
      if (enter) animations.push(enter);
    }
    return () => animations.forEach(animation => animation.cancel());
  }, [text, active]);
  useLayoutEffect(() => {
    const el = ref.current;
    if (!el) return;
    const viewport = el.closest('.chatty-chat-viewport, .chatty-surface__viewport');
    let animation;
    const enter = () => {
      const matchingClock = !sendKey || viewport?.dataset.chattySendKey === sendKey;
      if (!matchingClock && viewport?.dataset.chattyPendingSendKey === sendKey) return;
      animation?.cancel();
      const duration = Number(viewport?.dataset.chattySendDuration) || 180;
      const hasClock = matchingClock && viewport?.hasAttribute('data-chatty-send-start');
      const previousEntry = viewport && entered.get(viewport);
      const seen = sendKey && previousEntry?.key === sendKey;
      const fadeStart = hasClock
        ? Number(viewport.dataset.chattySendStart) + duration
        : seen
          ? previousEntry.at
          : performance.now();
      const elapsed = performance.now() - fadeStart;
      const progress = seen ? Math.max(0, Math.min(1, elapsed / 150)) : 0;
      el.style.opacity = '';
      if (progress >= 1) return;
      if (viewport && sendKey) entered.set(viewport, {key: sendKey, at: fadeStart});
      animation = el.animate?.([{opacity: progress}, {opacity: 1}], {
        duration: 150 * (1 - progress),
        delay: hasClock ? Math.max(0, -elapsed) : 0,
        fill: 'backwards'
      });
    };
    if (sendKey) el.style.opacity = '0';
    enter();
    viewport?.addEventListener('chatty:send-start', enter);
    return () => {
      animation?.cancel();
      viewport?.removeEventListener('chatty:send-start', enter);
    };
  }, [active, sendKey]);
  if (!active) return null;
  return (
    <span ref={ref} className="chatty-thinking" role="status" aria-live="polite">
      {text ? (
        <span className="chatty-thinking__labels">
          <span className="chatty-thinking__previous" aria-hidden="true" hidden={outgoing === text}>
            {outgoing}
          </span>
          <span className="chatty-thinking__label">{text}</span>
        </span>
      ) : (
        <span className="chatty-thinking__dot" aria-label="…" />
      )}
    </span>
  );
}

/**
 * Render safe markdown with optional streaming animation and link tracking.
 * @param {string} text
 * @param {string} className
 * @param {boolean} animate
 * @param {(href: string, event: MouseEvent) => void} onLinkClick called when a link is followed by click or middle click
 */
export function Markdown({text = '', className, animate = false, onLinkClick}) {
  // Keep mounted word spans after generation ends so their running fades can finish in place.
  const wordFade = useRef(false);
  if (animate) wordFade.current = true;
  // A stored hard break (backslash-newline) stays a line break; a plain newline starts a paragraph.
  const source = stripLatex(text).replace(/\\\n/g, HARD_BREAK);
  const blocks = parseBlocks(source);
  return (
    <div className={className}>
      {blocks.map((b, i) => (
        <MemoBlock
          key={i}
          block={b}
          animate={animate}
          streamingEnd={animate && i === blocks.length - 1 && source.endsWith(b)}
          wordFade={wordFade.current}
          onLinkClick={onLinkClick}
        />
      ))}
    </div>
  );
}

// Block-level memoisation. Same string -> skip the re-render entirely.
// Streaming markdown grows from the end, so all blocks before the last
// one bail out and React only reconciles the active trailing block.
const MemoBlock = memo(
  function MemoBlock({block, animate, streamingEnd, wordFade, onLinkClick}) {
    return renderBlock({block, animate, streamingEnd, wordFade, onLinkClick});
  },
  (prev, next) =>
    prev.block === next.block &&
    prev.animate === next.animate &&
    prev.streamingEnd === next.streamingEnd &&
    prev.wordFade === next.wordFade &&
    prev.onLinkClick === next.onLinkClick
);

/**
 * Split a text run into word spans keyed by position, so a growing run keeps its mounted words and only new ones fade.
 * @param {string} run
 * @param {number} offset run start within its line
 * @returns {Array}
 */
function fadeWords(run, offset) {
  // Lookbehind would break Safari below 16.4, so words are matched rather than split.
  return (run.match(/\S+\s*|\s+/g) ?? []).map((word, i) => (
    <span key={`${offset}-${i}`} ref={fadeIn}>
      {word}
    </span>
  ));
}

const FADE_MS = 700;

// Stable ref callback, so it runs once per mounted word rather than on every render.
function fadeIn(el) {
  if (!el?.animate || prefersReducedMotion()) return;
  el.animate([{opacity: 0}, {opacity: 1}], {duration: FADE_MS, easing: 'ease-out'});
}

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

Observed · AI Mode / admin

  • Event-relative
  • opacity
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.
Moment start · 2 property rows · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
Old status · opacity
150 ms
New status · opacity
150 ms
word span mounts · 1 property row · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
New word · opacity
700 ms

What animates

ElementPropertyFrom / ToDuration / DelayEasing
Old statusopacity1 → 0150 ms 0 mslinear
New statusopacity0 → 1150 ms 0 mslinear
New wordopacity0 → 1700 ms after word span mounts + 0 msease-out

Page or tab swap

AI Mode · Motion example

Show code
PageView.jsxWrap code linesCopy
import React, {
  createContext,
  Suspense,
  useCallback,
  useLayoutEffect,
  useRef,
  useState
} from 'react';

export const PageActivityContext = createContext(true);

/**
 * Retain visited pages and commit a requested page only when its content can paint.
 * @param {string} value requested page
 * @param {Function} onDisplayed page geometry owner
 */
export function usePageViews(value, onDisplayed) {
  const [displayed, setDisplayed] = useState(value);
  const [visited, setVisited] = useState([]);
  const requested = useRef(value);
  const notify = useRef(onDisplayed);
  requested.current = value;
  notify.current = onDisplayed;
  const onReady = useCallback(page => {
    setVisited(previous => (previous.includes(page) ? previous : [...previous, page]));
    if (page !== requested.current) return;
    setDisplayed(page);
    notify.current?.(page);
  }, []);
  useLayoutEffect(() => {
    if (!visited.includes(value)) return;
    setDisplayed(value);
    notify.current?.(value);
  }, [value, visited]);
  return {displayed, pages: visited.includes(value) ? visited : [...visited, value], onReady};
}

/**
 * Keep a hidden page mounted without letting a cold chunk erase the visible page.
 * @param {string} page
 * @param {boolean} active
 * @param {Function} onReady
 * @param {React.ReactNode} children
 */
export function PageView({page, active, onReady, children}) {
  const view = useRef(null);
  useLayoutEffect(() => {
    if (!active || !window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return;
    // The legacy reduced-motion wildcard starts a fade on every newly visible descendant.
    view.current?.getAnimations?.({subtree: true}).forEach(animation => {
      if (animation.animationName === 'chatty-fade') animation.finish();
    });
  }, [active]);
  return (
    <div
      ref={view}
      data-chatty-page-view={page}
      hidden={!active}
      style={{display: active ? 'contents' : 'none'}}
    >
      <PageActivityContext.Provider value={active}>
        <Suspense fallback={null}>
          <ReadyPage page={page} onReady={onReady}>
            {children}
          </ReadyPage>
        </Suspense>
      </PageActivityContext.Provider>
    </div>
  );
}

function ReadyPage({page, onReady, children}) {
  const marker = useRef(null);
  useLayoutEffect(() => {
    const frame = requestAnimationFrame(() => {
      if (marker.current?.isConnected) onReady(page);
    });
    return () => cancelAnimationFrame(frame);
  }, [page, onReady]);
  return (
    <>
      {children}
      <span ref={marker} hidden />
    </>
  );
}

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

Observed · Shared PageView; AI Mode sidebar content

  • Event-relative
  • display + opacity
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.
requested page ready · 2 property rows · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
Old main page · display
◆
Instant
Ready main page · display
◆
Instant
Moment start · 1 property row · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
Sidebar old content · opacity
100 ms
sidebar old-content fade finishes · 1 property row · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
Sidebar new content · opacity
200 ms

What animates

ElementPropertyFrom / ToDuration / DelayEasing
Old main pagedisplaycontents → none0 ms after requested page ready + 0 mslinear
Ready main pagedisplaynone → contents0 ms after requested page ready + 0 mslinear
Sidebar old contentopacity1 → 0100 ms 0 msease-in
Sidebar new contentopacity0 → 1200 ms after sidebar old-content fade finishes + 0 msease-out

Add-to-cart chain

AI Mode · Motion example

Show code
AddToCartFeedback.jsx; flyToCart.js; cartFeedback.js; cartMotion.jsWrap code linesCopy
import {IconCheck} from '../icons/chatIcons.jsx';

/**
 * Keep the action label's space while a confirmed add draws a check, holds, and returns.
 * @param {*} label
 * @param {string} successLabel translated live announcement
 * @param {string} successText visible Classic success copy
 * @param {boolean} added
 */
export function AddToCartFeedback({label, added, successLabel = '', successText = ''}) {
  const [showCheck, setShowCheck] = useState(added);
  useEffect(() => {
    setShowCheck(added);
    if (!added) return;
    const timer = setTimeout(() => setShowCheck(false), successText ? ADDED_RESET_MS : 1650);
    return () => clearTimeout(timer);
  }, [added, successText]);
  return (
    <span className={`chatty-atc-feedback${showCheck ? ' is-added' : ''}`}>
      <span className="chatty-atc-label" title={typeof label === 'string' ? label : undefined}>
        {label}
      </span>
      {showCheck && (
        <span className="chatty-atc-check" aria-hidden="true">
          <IconCheck size={20} />
          {successText && <span>{successText}</span>}
        </span>
      )}
      <span className="chatty-atc-announcement" role="status">
        {added ? successLabel : ''}
      </span>
    </span>
  );
}

/**
 * Flies a clone of the product image into the first visible bag icon, then rocks the bag and floats a "+1"; best-effort only, silently no-ops on reduced motion, missing/covered bag, or too many ghosts in flight, never blocking ATC.
 * @param {Element|null} sourceEl product image to clone
 * @param {{el: Element, rect: {left: number, top: number, width: number, height: number}}|null} explicitTarget lands here instead of the bag, without the bag reaction
 */
export function flyToCart(sourceEl, explicitTarget = null) {
  try {
    if (!sourceEl || REDUCED_MOTION_QUERY.matches) return;

    const isMobile = window.matchMedia('(max-width: 899px)').matches;
    const maxGhosts = isMobile ? MAX_CONCURRENT_MOBILE : MAX_CONCURRENT;
    if (document.querySelectorAll('[data-chatty-ghost]').length >= maxGhosts) return;

    // Batch all rect reads before any DOM write to avoid layout thrash.
    const srcRect = sourceEl.getBoundingClientRect();
    if (!srcRect.width || !srcRect.height) return;
    const target = explicitTarget || findVisibleBagTarget();
    if (!target) return;

    const flight = computeFlight(srcRect, target.rect);
    const outer = createGhost(sourceEl, flight);
    document.body.appendChild(outer);

    const onLand = explicitTarget ? null : () => reactBagLanding(target.el);
    if (flight.distance < MIN_FLY_DISTANCE) {
      return fadeOutInPlace(outer, onLand).finished?.catch(() => {});
    } else {
      return flyAlongArc(outer, flight, onLand).finished?.catch(() => {});
    }
  } catch {
    // Animation is decoration — swallow so a failure never breaks add-to-cart.
  }
}

/**
 * Swap after landing and an 800ms confirmation hold, unless the shopper interacts first.
 * @param {Promise<void>} landing
 * @param {Function} swap
 * @returns {Function} cancel
 */
export function afterCartFeedback({landing, swap}) {
  let cancelled = false;
  let timer;
  const cancel = () => {
    cancelled = true;
    clearTimeout(timer);
    document.removeEventListener('pointerdown', cancel, true);
    document.removeEventListener('keydown', cancel, true);
  };
  document.addEventListener('pointerdown', cancel, true);
  document.addEventListener('keydown', cancel, true);
  Promise.resolve(landing).then(() => {
    if (cancelled) return;
    timer = setTimeout(() => {
      cancel();
      swap();
    }, 800);
  }, cancel);
  return cancel;
}

/**
 * Linear X on the wrapper + ease-in Y on the clone compose into a parabolic
 * arc using compositor-only transforms.
 * @param {Element} outer ghost wrapper
 * @param {number} dx
 * @param {number} dy
 * @param {number} distance
 * @param {Function|null} onLand
 */
function flyAlongArc(outer, {dx, dy, distance}, onLand) {
  const duration = Math.min(
    Math.max(Math.round((MOTION.flyBase * distance) / MOTION.flyBaseDistance), MOTION.flyMin),
    MOTION.flyMax
  );

  outer.animate([{transform: 'translateX(0)'}, {transform: `translateX(${dx}px)`}], {
    duration,
    easing: MOTION.flyX,
    fill: 'forwards'
  });
  return removeOnFinish(
    outer.firstChild.animate(
      [
        {transform: 'translateY(0) scale(1)', opacity: 1},
        {transform: `translateY(${dy * 0.5}px) scale(0.55)`, opacity: 0.9, offset: 0.5},
        {transform: `translateY(${dy * 0.8}px) scale(0.28)`, opacity: 0.6, offset: 0.8},
        {transform: `translateY(${dy}px) scale(0.15)`, opacity: 0}
      ],
      {duration, easing: MOTION.flyY, fill: 'forwards'}
    ),
    outer,
    onLand
  );
}

/**
 * Spring-bump the badge when the bag count increases.
 * @param {Element|null} badgeEl
 */
export function bumpBadge(badgeEl) {
  if (!badgeEl || REDUCED_MOTION_QUERY.matches) return;
  badgeEl.animate(BADGE_BUMP_KEYFRAMES, {duration: MOTION.badgeBump, easing: MOTION.spring});
}

// Keep `spring` in sync with --spring in styles/foundation.scss.
export const MOTION = {
  flyX: 'linear',
  flyY: 'cubic-bezier(0.55, 0, 1, 0.45)',
  spring: 'cubic-bezier(0.34, 1.56, 0.64, 1)',
  flyBase: 580,
  flyMin: 300,
  flyMax: 720,
  flyBaseDistance: 400,
  badgeBump: 320,
  bagWiggle: 500,
  plusOne: 700,
  ghostZ: 2147483647
};

Classic · Motion example

Show code
AddToCartFeedback.jsx; flyToCart.js; cartFeedback.js; cartMotion.jsWrap code linesCopy
import {IconCheck} from '../icons/chatIcons.jsx';

/**
 * Keep the action label's space while a confirmed add draws a check, holds, and returns.
 * @param {*} label
 * @param {string} successLabel translated live announcement
 * @param {string} successText visible Classic success copy
 * @param {boolean} added
 */
export function AddToCartFeedback({label, added, successLabel = '', successText = ''}) {
  const [showCheck, setShowCheck] = useState(added);
  useEffect(() => {
    setShowCheck(added);
    if (!added) return;
    const timer = setTimeout(() => setShowCheck(false), successText ? ADDED_RESET_MS : 1650);
    return () => clearTimeout(timer);
  }, [added, successText]);
  return (
    <span className={`chatty-atc-feedback${showCheck ? ' is-added' : ''}`}>
      <span className="chatty-atc-label" title={typeof label === 'string' ? label : undefined}>
        {label}
      </span>
      {showCheck && (
        <span className="chatty-atc-check" aria-hidden="true">
          <IconCheck size={20} />
          {successText && <span>{successText}</span>}
        </span>
      )}
      <span className="chatty-atc-announcement" role="status">
        {added ? successLabel : ''}
      </span>
    </span>
  );
}

/**
 * Flies a clone of the product image into the first visible bag icon, then rocks the bag and floats a "+1"; best-effort only, silently no-ops on reduced motion, missing/covered bag, or too many ghosts in flight, never blocking ATC.
 * @param {Element|null} sourceEl product image to clone
 * @param {{el: Element, rect: {left: number, top: number, width: number, height: number}}|null} explicitTarget lands here instead of the bag, without the bag reaction
 */
export function flyToCart(sourceEl, explicitTarget = null) {
  try {
    if (!sourceEl || REDUCED_MOTION_QUERY.matches) return;

    const isMobile = window.matchMedia('(max-width: 899px)').matches;
    const maxGhosts = isMobile ? MAX_CONCURRENT_MOBILE : MAX_CONCURRENT;
    if (document.querySelectorAll('[data-chatty-ghost]').length >= maxGhosts) return;

    // Batch all rect reads before any DOM write to avoid layout thrash.
    const srcRect = sourceEl.getBoundingClientRect();
    if (!srcRect.width || !srcRect.height) return;
    const target = explicitTarget || findVisibleBagTarget();
    if (!target) return;

    const flight = computeFlight(srcRect, target.rect);
    const outer = createGhost(sourceEl, flight);
    document.body.appendChild(outer);

    const onLand = explicitTarget ? null : () => reactBagLanding(target.el);
    if (flight.distance < MIN_FLY_DISTANCE) {
      return fadeOutInPlace(outer, onLand).finished?.catch(() => {});
    } else {
      return flyAlongArc(outer, flight, onLand).finished?.catch(() => {});
    }
  } catch {
    // Animation is decoration — swallow so a failure never breaks add-to-cart.
  }
}

/**
 * Swap after landing and an 800ms confirmation hold, unless the shopper interacts first.
 * @param {Promise<void>} landing
 * @param {Function} swap
 * @returns {Function} cancel
 */
export function afterCartFeedback({landing, swap}) {
  let cancelled = false;
  let timer;
  const cancel = () => {
    cancelled = true;
    clearTimeout(timer);
    document.removeEventListener('pointerdown', cancel, true);
    document.removeEventListener('keydown', cancel, true);
  };
  document.addEventListener('pointerdown', cancel, true);
  document.addEventListener('keydown', cancel, true);
  Promise.resolve(landing).then(() => {
    if (cancelled) return;
    timer = setTimeout(() => {
      cancel();
      swap();
    }, 800);
  }, cancel);
  return cancel;
}

/**
 * Linear X on the wrapper + ease-in Y on the clone compose into a parabolic
 * arc using compositor-only transforms.
 * @param {Element} outer ghost wrapper
 * @param {number} dx
 * @param {number} dy
 * @param {number} distance
 * @param {Function|null} onLand
 */
function flyAlongArc(outer, {dx, dy, distance}, onLand) {
  const duration = Math.min(
    Math.max(Math.round((MOTION.flyBase * distance) / MOTION.flyBaseDistance), MOTION.flyMin),
    MOTION.flyMax
  );

  outer.animate([{transform: 'translateX(0)'}, {transform: `translateX(${dx}px)`}], {
    duration,
    easing: MOTION.flyX,
    fill: 'forwards'
  });
  return removeOnFinish(
    outer.firstChild.animate(
      [
        {transform: 'translateY(0) scale(1)', opacity: 1},
        {transform: `translateY(${dy * 0.5}px) scale(0.55)`, opacity: 0.9, offset: 0.5},
        {transform: `translateY(${dy * 0.8}px) scale(0.28)`, opacity: 0.6, offset: 0.8},
        {transform: `translateY(${dy}px) scale(0.15)`, opacity: 0}
      ],
      {duration, easing: MOTION.flyY, fill: 'forwards'}
    ),
    outer,
    onLand
  );
}

/**
 * Spring-bump the badge when the bag count increases.
 * @param {Element|null} badgeEl
 */
export function bumpBadge(badgeEl) {
  if (!badgeEl || REDUCED_MOTION_QUERY.matches) return;
  badgeEl.animate(BADGE_BUMP_KEYFRAMES, {duration: MOTION.badgeBump, easing: MOTION.spring});
}

// Keep `spring` in sync with --spring in styles/foundation.scss.
export const MOTION = {
  flyX: 'linear',
  flyY: 'cubic-bezier(0.55, 0, 1, 0.45)',
  spring: 'cubic-bezier(0.34, 1.56, 0.64, 1)',
  flyBase: 580,
  flyMin: 300,
  flyMax: 720,
  flyBaseDistance: 400,
  badgeBump: 320,
  bagWiggle: 500,
  plusOne: 700,
  ghostZ: 2147483647
};

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

Observed · AI Mode / Classic; inbox receipt is read-only

  • Event-relative
  • opacity + stroke-dashoffset + display
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.
server confirms add · 3 property rows · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
Action label · opacity
150 ms
Check · opacity
150 ms
Check polyline · stroke-dashoffset
300 ms
added becomes true · 1 property row · offsets from this event
0 ms500 ms1000 ms1500 ms2000 ms
Check · display
◆
Instant
flight starts · 1 property row · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
Flight image · opacity
300–720 ms
landing Promise resolves unless user cancels · 1 property row · offsets from this event
0 ms250 ms500 ms750 ms1000 ms
View · opacity
◆
Instant

What animates

ElementPropertyFrom / ToDuration / DelayEasing
Action labelopacity1 → 0150 ms after server confirms add + 0 msease
Checkopacity0 → 1150 ms after server confirms add + 0 msease
Check polylinestroke-dashoffset24 → 0300 ms after server confirms add + 0 msease
Checkdisplaygrid → none0 ms after added becomes true + 1650 mslinear
Flight imageopacity1 → 0300–720 ms after flight starts + 0 mscubic-bezier(0.55, 0, 1, 0.45)
Viewopacity1 → 10 ms after landing Promise resolves unless user cancels + 800 mslinear

Admin thread switch

Admin · Motion example

Show code
InboxV2ChatArea.jsxWrap code linesCopy
    if (adapterLoading) return <LoadingSkeleton />;

function LoadingSkeleton() {
  return (
    <div className="inbox-v2__loading" aria-label="Loading messages" aria-busy="true">
      {SKELETON_ROWS.map((row, i) => (
        <div key={i} className={`inbox-v2__loading-row inbox-v2__loading-row--${row.side}`}>
          <div className="inbox-v2__loading-avatar" />
          <div className="inbox-v2__loading-bubble">
            {row.widths.map((w, j) => (
              <div key={j} className="inbox-v2__loading-line" style={{width: w}} />
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

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

Observed · Admin inbox

  • Event-relative
  • opacity + visibility
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.

What animates

ElementPropertyFrom / ToDuration / DelayEasing
Thread surfaceopacity1 → 10 ms after route paramId changes + 0 mslinear
Loading skeletonvisibilityhidden → visible0 ms after adapterLoading branch renders + 0 mslinear

Copy-paste export

Classic

.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

.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

.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

LightDarkDesktopMobile

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.

Show code
motion-rules.jsxWrap code linesCopy
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>;
}