Ordo UI
AI助手与对话

Conversation

@mox-hub/patterns · AI · 助手与对话 · canonical

conversation@mox-hub/patternsLayout & Shellscanonicalsrc/components/conversation.tsx
变体演示conversation
你
帮我总结这次发布的风险。
小周
主要风险集中在数据库迁移与回滚窗口,建议先跑一次预演。
系统
已切换到只读模式

Props API

Prop类型默认值说明
children*ReactNode——
stickToBottom*booleantrue—
stickThreshold*number48—
maxHeight*string | number'60vh'—
labels*Partial<ConversationLabels>——
className*string——
onScroll*UIEventHandler<HTMLDivElement>——
style*CSSProperties——

源码

packages/patterns/src/components/conversation.tsx
/**
 * Conversation —— 可组合对话滚动容器原子(治理方案 W4 P0 · B3)
 *
 * 与 `assistant-message-list` 的分工:
 * - 本件是**布局与滚动原子**:只提供 role="log" 滚动区、贴底跟随与「回到底部」按钮;
 *   消息数据、渲染器与消息节点全部由调用方经 children 注入,不持有任何会话状态。
 * - `assistant-message-list` 保留旧 API 不变,继续内置 parts 解析 / 工具卡编排 / pending 行;
 *   新代码改用 `<Conversation><Message … /></Conversation>` 的原子组合,两套实现并存,
 *   本件不依赖旧列表,旧列表也无需迁移。
 *
 * 滚动契约:
 * - `stickToBottom`(默认 true):内容增长且原本贴底才自动跟到底;用户上翻后不抢滚动位置。
 * - 离开底部超过 `stickThreshold` px 后显示可聚焦的「回到底部」按钮(带 aria-label)。
 * - 所有 DOM 访问都在 effect / 事件回调里,渲染期不读 window,SSR / jsdom 安全。
 * - 文案缺省中文常量,消费方经 labels 覆写接入 i18n。
 */
import {
  useCallback,
  useEffect,
  useRef,
  useState,
  type ComponentProps,
  type ReactNode,
  type UIEvent,
} from 'react';
import { ArrowDown } from 'lucide-react';

import { cn } from '@mox-hub/ui';
import { Button } from '@mox-hub/ui/components/button';

import { usePatternLabels } from '../lib/i18n';

/** 组件内文案缺省(中文常量;消费方经 labels 覆写接入 i18n)。 */
export interface ConversationLabels {
  /** 回到底部按钮文案 */
  scrollToBottom: string;
  /** 滚动区可访问名(role="log" 的 aria-label) */
  region: string;
}

export const CONVERSATION_DEFAULT_LABELS: ConversationLabels = {
  scrollToBottom: '回到底部',
  region: '对话',
};

export interface ConversationProps
  extends Omit<ComponentProps<'div'>, 'children'> {
  /** 消息节点(通常是一组 <Message />);数据由调用方持有 */
  children: ReactNode;
  /** 吸底滚动,默认 true */
  stickToBottom?: boolean;
  /** 距底部多少 px 内视为贴底,默认 48 */
  stickThreshold?: number;
  /** 容器最大高度;数字按 px,默认 60vh */
  maxHeight?: number | string;
  /** 回到底部按钮文案 / 滚动区域名覆写 */
  labels?: Partial<ConversationLabels>;
  className?: string;
}

export function Conversation({
  children,
  stickToBottom = true,
  stickThreshold = 48,
  maxHeight = '60vh',
  labels,
  className,
  onScroll,
  style,
  'aria-label': ariaLabel,
  ...props
}: ConversationProps) {
  const D = usePatternLabels('conversation', CONVERSATION_DEFAULT_LABELS);
  const text: ConversationLabels = {
    scrollToBottom: labels?.scrollToBottom ?? D.scrollToBottom,
    region: labels?.region ?? D.region,
  };

  const scrollRef = useRef<HTMLDivElement>(null);
  const contentRef = useRef<HTMLDivElement>(null);
  const [atBottom, setAtBottom] = useState(true);

  const scrollToBottom = useCallback((behavior: ScrollBehavior = 'smooth') => {
    const node = scrollRef.current;
    if (!node) return;
    if (typeof node.scrollTo === 'function') {
      node.scrollTo({ top: node.scrollHeight, behavior });
      return;
    }
    // 无 scrollTo 的环境(部分测试运行时)退化为直接赋值。
    node.scrollTop = node.scrollHeight;
  }, []);

  const updateAtBottom = useCallback(() => {
    const node = scrollRef.current;
    if (!node) return;
    setAtBottom(
      node.scrollHeight - node.scrollTop - node.clientHeight <= stickThreshold,
    );
  }, [stickThreshold]);

  // children 内容增长没有稳定引用可比对(流式子节点可能只更新内部状态),
  // 因此每次提交后检查:原本贴底才跟随;用户上翻后(atBottom=false)不抢位置。
  useEffect(() => {
    if (!stickToBottom || !atBottom) return;
    scrollToBottom('auto');
  });

  // 纯布局高度变化(流式文本回流、字体加载)不触发 React 提交时,由 ResizeObserver 兜底。
  useEffect(() => {
    if (!stickToBottom) return;
    const node = scrollRef.current;
    if (!node || typeof ResizeObserver === 'undefined') return;
    const observer = new ResizeObserver(() => {
      if (atBottom) scrollToBottom('auto');
    });
    observer.observe(node);
    if (contentRef.current) observer.observe(contentRef.current);
    return () => observer.disconnect();
  }, [stickToBottom, atBottom, scrollToBottom]);

  const handleScroll = useCallback(
    (event: UIEvent<HTMLDivElement>) => {
      onScroll?.(event);
      if (!stickToBottom) return;
      updateAtBottom();
    },
    [onScroll, stickToBottom, updateAtBottom],
  );

  const resolvedMaxHeight =
    typeof maxHeight === 'number' ? `${maxHeight}px` : maxHeight;

  return (
    <div
      {...props}
      data-ai-component="conversation"
      className={cn('relative', className)}
    >
      <div
        ref={scrollRef}
        role="log"
        aria-live="polite"
        aria-relevant="additions text"
        aria-label={ariaLabel ?? text.region}
        tabIndex={0}
        onScroll={handleScroll}
        style={{ maxHeight: resolvedMaxHeight, ...style }}
        className="overflow-y-auto overscroll-contain pe-1 outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
        data-ai-component="conversation.scroll"
      >
        <div
          ref={contentRef}
          className="flex flex-col gap-3"
          data-ai-component="conversation.messages"
        >
          {children}
        </div>
      </div>
      {stickToBottom && !atBottom ? (
        <Button
          type="button"
          variant="outline"
          size="xs"
          className="absolute end-2 bottom-2 bg-background shadow-xs"
          aria-label={text.scrollToBottom}
          onClick={() => scrollToBottom()}
          data-ai-action="conversation.scrollToBottom.click"
        >
          <ArrowDown aria-hidden />
          {text.scrollToBottom}
        </Button>
      ) : null}
    </div>
  );
}

可访问性与 RTL

  • 键盘:交互件保留:focus-visible焦点环;浮层支持 Escape 关闭与焦点归还,菜单 / 页签按 Base UI 约定支持方向键。 筛选菜单、拖拽排序、执行树与模型 listbox 等关键键盘流由 Playwright 断言覆盖,见规范示例 · 交互与可访问性。
  • RTL:间距、对齐与方向性图标使用逻辑属性 (ms-* /text-start /rtl:-scale-x-100);通过 ThemeProvider 或I18nProvider 的direction="rtl"驱动,`lint:rtl` 会拦截新增物理类。
  • 文案:优先用组件labels /translate /translator props,其次用I18nProvider目录;内置 zh-CN 默认值,en-US 为参考翻译。见Theming · i18n 与 RTL。
  • 对比度:高对比度 token、2px 控件边框与 3px 焦点环由主题层统一提供,见Foundations · Contrast。

用法说明

对话滚动容器:role=log + aria-live、吸底滚动、回到底部;消息内容由 children 注入。