Ordo UI
AI助手与对话

Message

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

message@mox-hub/patternsLayout & Shellscanonicalsrc/components/message.tsx
变体演示message
你
这条是用户消息
小周
这条是助手消息,带操作槽。
系统
这条是系统消息

Props API

Prop类型默认值说明
role*MessageRole——
children*ReactNode——
name*string——
avatar*ReactNode——
actions*ReactNode——
pending*ReactNode——
timestamp*string——
variant*"bubble" | "plain"'bubble'—
labels*Partial<MessageLabels>——
className*string——

源码

packages/patterns/src/components/message.tsx
/**
 * Message —— 可组合单条消息原子(治理方案 W4 P0 · B3)
 *
 * 与 `assistant-message-list` 的分工:
 * - 本件只负责单条消息的**展示骨架**:角色对齐、名称 / 头像 / 时间戳、气泡或 plain
 *   内容、操作槽与 pending 行;不解析消息 parts、不依赖工具卡或消息列表。
 * - 旧 `assistant-message-list` 继续内置 parts 解析与工具卡编排并保持 API 兼容;
 *   新代码用 `<Conversation>` + 本件自行组合渲染器(Markdown / 工具卡等)。
 * - 纯展示受控件:内容与所有槽位由 props 注入,不取数、不发请求、不持有业务状态。
 *
 * 角色约定:
 * - user 右对齐(头像槽位于内联末端),assistant / tool 左对齐;
 *   assistant 未传 avatar 时默认渲染 Bot 图标占位。
 * - system 统一用 muted 小字**左对齐**,且不套气泡背景(与 assistant 视觉区分;
 *   选择左对齐而非居中,避免与消息流左缘脱节)。
 * - 名称默认取 labels 中对应角色的显示名;显式传 `name=""` 可关闭名称行。
 * - 根元素带 `data-message-role`;名称是可见文本,内容区不再重复 aria-label 播报。
 */
import type { ComponentProps, ReactNode } from 'react';
import { Bot } from 'lucide-react';

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

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

export type MessageRole = 'user' | 'assistant' | 'system' | 'tool';

/** 组件内文案缺省(中文常量;消费方经 labels 覆写接入 i18n)。 */
export interface MessageLabels {
  /** assistant 缺省显示名 */
  assistantName: string;
  /** user 缺省显示名 */
  userName: string;
  /** system 缺省显示名 */
  systemName: string;
  /** pending 传 true 时的缺省行文案 */
  pending: string;
}

export const MESSAGE_DEFAULT_LABELS: MessageLabels = {
  assistantName: '助手',
  userName: '你',
  systemName: '系统',
  pending: '等待响应…',
};

export interface MessageProps
  extends Omit<ComponentProps<'div'>, 'children'> {
  role: MessageRole;
  children: ReactNode;
  /** 显示名(assistant 名称 / user 名称);缺省取 labels 对应角色名 */
  name?: string;
  /** 头像节点(Avatar 等);assistant 缺省 Bot 图标 */
  avatar?: ReactNode;
  /** 操作槽(MessageActions 等) */
  actions?: ReactNode;
  /**
   * 等待首包 / 工具执行中:渲染 children 之外的 pending 行。
   * 传 true 时渲染 labels.pending 文案,传节点时原样渲染。
   */
  pending?: ReactNode;
  /** 时间戳文本 */
  timestamp?: string;
  /** 气泡样式:bubble 默认 / plain 无背景 */
  variant?: 'bubble' | 'plain';
  labels?: Partial<MessageLabels>;
  className?: string;
}

function defaultRoleName(
  role: MessageRole,
  text: MessageLabels,
): string | undefined {
  switch (role) {
    case 'user':
      return text.userName;
    case 'assistant':
      return text.assistantName;
    case 'system':
      return text.systemName;
    default:
      // tool 没有约定的缺省名,仅在显式传 name 时展示。
      return undefined;
  }
}

function contentClasses(role: MessageRole, variant: MessageProps['variant']) {
  // system 固定 muted 小字,不随 variant 变成气泡(注释见文件头)。
  if (role === 'system') {
    return 'min-w-0 break-words text-xs text-content-text-muted';
  }
  if (variant === 'plain') {
    return 'min-w-0 break-words text-sm text-content-text';
  }
  const base = 'min-w-0 rounded-lg px-3 py-2 text-sm text-content-text break-words';
  return cn(
    base,
    role === 'user'
      ? 'whitespace-pre-wrap bg-accent-blue-light'
      : 'bg-content-bg-secondary',
  );
}

export function Message({
  role,
  children,
  name,
  avatar,
  actions,
  pending,
  timestamp,
  variant = 'bubble',
  labels,
  className,
  ...props
}: MessageProps) {
  const D = usePatternLabels('message', MESSAGE_DEFAULT_LABELS);
  const text: MessageLabels = {
    assistantName: labels?.assistantName ?? D.assistantName,
    userName: labels?.userName ?? D.userName,
    systemName: labels?.systemName ?? D.systemName,
    pending: labels?.pending ?? D.pending,
  };

  const isUser = role === 'user';
  const displayName = name !== undefined ? name : defaultRoleName(role, text);
  const showHeader = Boolean(displayName) || Boolean(timestamp);

  const avatarNode =
    avatar !== undefined && avatar !== null && avatar !== false ? (
      <span
        className="flex shrink-0 items-start"
        data-ai-component="message.avatar"
      >
        {avatar}
      </span>
    ) : role === 'assistant' ? (
      <span
        aria-hidden="true"
        className="flex size-6 shrink-0 items-center justify-center rounded-lg bg-accent-purple-light text-accent-purple"
        data-ai-component="message.avatar"
      >
        <Bot className="size-3.5" />
      </span>
    ) : null;

  const headerNode = showHeader ? (
    <div
      className={cn('flex items-center gap-2', isUser && 'justify-end')}
      data-ai-component="message.header"
    >
      {displayName ? (
        <span className="text-2xs font-medium text-content-text-muted">
          {displayName}
        </span>
      ) : null}
      {timestamp ? (
        <time
          className="text-2xs tabular-nums text-content-text-muted"
          data-ai-component="message.timestamp"
        >
          {timestamp}
        </time>
      ) : null}
    </div>
  ) : null;

  const contentNode =
    children === undefined || children === null || children === false ? null : (
      <div
        className={contentClasses(role, variant)}
        data-ai-component="message.content"
      >
        {children}
      </div>
    );

  const pendingNode =
    pending === undefined || pending === null || pending === false ? null : (
      <div
        className="text-sm text-content-text-muted"
        data-ai-component="message.pending"
      >
        {pending === true ? text.pending : pending}
      </div>
    );

  const actionsNode =
    actions !== undefined && actions !== null && actions !== false ? (
      <div
        className={cn('flex items-center gap-1', isUser && 'justify-end')}
        data-ai-component="message.actions-slot"
      >
        {actions}
      </div>
    ) : null;

  return (
    <div
      {...props}
      data-message-role={role}
      data-ai-component={`message.${role}`}
      className={cn(
        'group/message flex w-full flex-col gap-1',
        isUser ? 'items-end' : 'items-start',
        className,
      )}
    >
      <div
        className={cn(
          'flex w-full items-start gap-2',
          isUser && 'flex-row-reverse',
        )}
      >
        {avatarNode}
        <div
          className={cn(
            'flex min-w-0 flex-col gap-1',
            role === 'system' ? 'max-w-full items-start' : 'max-w-4/5',
            isUser ? 'items-end' : 'items-start',
          )}
        >
          {headerNode}
          {contentNode}
          {pendingNode}
          {actionsNode}
        </div>
      </div>
    </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。

用法说明

消息原子:user/assistant/system/tool 角色、头像、名称、操作槽与 pending 行;不持有会话状态。