Components
MarkdownText
Markdown 渲染组件,支持 GFM、KaTeX 数学公式、代码高亮和复制
MarkdownText 基于 @assistant-ui/react-markdown 封装,为 AI 回复的 Markdown 内容提供丰富的渲染能力。
引入
import { MarkdownText } from "aui-components";注意:MarkdownText 通常在 Thread 内部自动使用,你一般不需要手动引入它。只有在自定义消息渲染时才需要。
使用示例
import { MarkdownText } from "aui-components";
// 在自定义消息渲染中使用
<MessagePrimitive.Parts>
{({ part }) => {
if (part.type === "text") return <MarkdownText />;
return null;
}}
</MessagePrimitive.Parts>;Props
该组件没有公开的 Props。
插件配置
MarkdownText 预配置了以下插件:
| 类型 | 插件 | 用途 |
|---|---|---|
| remark | remark-gfm | GitHub Flavored Markdown(表格、删除线、任务列表) |
| remark | remark-math | 数学公式语法支持 |
| rehype | rehype-katex | KaTeX 数学公式渲染 |
预处理
preprocess={(text) =>
escapeCurrencyDollars(normalizeMathDelimiters(text))
}normalizeMathDelimiters— 将\(...\)和\[...\]转换为$...$和$$...$$escapeCurrencyDollars— 转义文本中的美元符号,避免与数学公式分隔符冲突
自定义 Markdown 样式
MarkdownText 对 HTML 元素进行了完整的样式定制:
标题
// h1 — text-xl font-semibold
// h2 — text-lg font-semibold
// h3 — text-base font-semibold
// h4 — text-base font-medium
// h5 — text-sm font-semibold
// h6 — text-sm font-medium代码
- 行内代码:圆角背景、等宽字体、
0.85em字号 - 代码块:带顶部标题栏的圆角容器
CodeHeader
每个代码块顶部都有一个标题栏,显示语言和复制按钮:
const CodeHeader: FC<CodeHeaderProps> = ({ language, code }) => {
// language — 代码语言标签
// code — 代码内容(用于复制)
return (
<div>
<span>{language}</span>
<TooltipIconButton tooltip="Copy" onClick={copy}>
<CopyIcon /> {/* 或 <CheckIcon /> 复制成功后 */}
</TooltipIconButton>
</div>
);
};支持的 Markdown 元素
| 元素 | 选择器 | 样式说明 |
|---|---|---|
| h1-h6 | aui-md-h[1-6] | 标题层级 |
| p | aui-md-p | 段落,my-3 leading-relaxed |
| a | aui-md-a | 链接,下划线和主题色 |
| blockquote | aui-md-blockquote | 引用,左侧边框 + 灰色文字 |
| ul/ol | aui-md-ul / aui-md-ol | 列表 |
| table/tr/th/td | aui-md-table 等 | 表格,border-separate |
| strong | aui-md-strong | 加粗 |
| code | aui-md-inline-code | 行内代码 |
| pre | aui-md-pre | 代码块容器 |
| hr | aui-md-hr | 分割线 |
| sup | aui-md-sup | 上标 |
完整示例
// 自定义消息渲染,覆盖默认的 Markdown 插件
import { MarkdownTextPrimitive } from "@assistant-ui/react-markdown";
function CustomMarkdown() {
return (
<MarkdownTextPrimitive
remarkPlugins={[remarkGfm]}
// 不启用数学公式
className="prose-sm"
components={{
h1: ({ children }) => (
<h1 className="text-2xl font-bold text-blue-600">{children}</h1>
),
}}
/>
);
}