AI助手与对话
CodeBlock
@mox-hub/patterns · AI · 助手与对话 · canonical
code-block@mox-hub/patternsAI Executioncanonicalsrc/components/code-block.tsx变体演示code-block
greet.tsts
export function greet(name: string) {
return `你好,${name}`
}Props API
| Prop | 类型 | 默认值 | 说明 |
|---|---|---|---|
| code* | string | — | — |
| language* | string | — | — |
| filename* | string | — | — |
| showLineNumbers* | boolean | false | — |
| highlightLines* | number[] | — | — |
| maxHeight* | string | number | — | — |
| copyable* | boolean | true | — |
| wrap* | boolean | false | — |
| labels* | Partial<CodeBlockLabels> | — | — |
| className* | string | — | — |
源码
import { useEffect, useState, type ComponentProps } from 'react';
import { Check, Copy } from 'lucide-react';
import { cn } from '@mox-hub/ui';
import { Button } from '@mox-hub/ui/components/button';
import type { Highlighter } from 'shiki';
import {
CODE_BLOCK_LANGUAGES,
ORDO_SHIKI_THEME,
normalizeCodeLanguage,
} from '../lib/highlight-theme';
import { usePatternLabels } from '../lib/i18n';
import { useCopyToClipboard } from '../lib/use-copy-to-clipboard';
/**
* CodeBlock —— 代码展示件(产物平面 + 工具卡共用)。
*
* - Shiki 高亮按需加载:首屏先渲染纯文本 `<pre>`,高亮完成后无闪烁替换;
* - 主题走 `ORDO_SHIKI_THEME`(CSS 变量),明暗主题自动跟随;
* - `language` 支持常用别名(ts/js/yml/md…),未知语言降级 text 而不报错;
* - 行号与高亮行只加 data 属性,样式由 `patterns.css` 的
* `.code-block-line-numbers` / `.code-block-line-highlight` 承担(含 RTL);
* - shiki 是 optional peer:只有引入本子路径的消费方需要安装。
*/
export interface CodeBlockLabels {
copy: string;
copied: string;
code: string;
}
export const CODE_BLOCK_DEFAULT_LABELS: CodeBlockLabels = {
copy: '复制代码',
copied: '已复制',
code: '代码',
};
export interface CodeBlockProps extends Omit<ComponentProps<'div'>, 'children'> {
code: string;
/** 语言 id 或别名;缺省 text */
language?: string;
/** 文件名(显示在头部左侧) */
filename?: string;
showLineNumbers?: boolean;
/** 高亮行(1-based) */
highlightLines?: number[];
/** 内容区最大高度;数字按 px */
maxHeight?: number | string;
copyable?: boolean;
/** 长行换行(默认横向滚动) */
wrap?: boolean;
labels?: Partial<CodeBlockLabels>;
}
let highlighterPromise: Promise<Highlighter> | null = null;
function getHighlighter(): Promise<Highlighter> {
highlighterPromise ??= import('shiki').then(({ createHighlighter }) =>
createHighlighter({
themes: [ORDO_SHIKI_THEME],
langs: [...CODE_BLOCK_LANGUAGES],
}),
);
return highlighterPromise;
}
export function CodeBlock({
code,
language,
filename,
showLineNumbers = false,
highlightLines,
maxHeight,
copyable = true,
wrap = false,
labels,
className,
...props
}: CodeBlockProps) {
const D = usePatternLabels('codeBlock', CODE_BLOCK_DEFAULT_LABELS);
const text: CodeBlockLabels = {
copy: labels?.copy ?? D.copy,
copied: labels?.copied ?? D.copied,
code: labels?.code ?? D.code,
};
const normalized = normalizeCodeLanguage(language);
const [html, setHtml] = useState<string | null>(null);
const { copied, copy } = useCopyToClipboard();
const highlightKey = highlightLines?.join(',') ?? '';
useEffect(() => {
let alive = true;
// 从稳定指纹还原集合,避免数组引用变化导致 effect 重跑
const highlightSet = new Set(
highlightKey ? highlightKey.split(',').map(Number) : [],
);
void (async () => {
try {
const highlighter = await getHighlighter();
let lang = normalized;
if (!highlighter.getLoadedLanguages().includes(lang)) {
try {
await highlighter.loadLanguage(lang as 'text');
} catch {
// 未知语言不抛给调用方:降级纯文本展示
lang = 'text';
}
}
const result = highlighter.codeToHtml(code, {
lang,
theme: 'ordo',
transformers: [
{
line(node, line) {
node.properties['data-line'] = line;
if (highlightSet.has(line)) {
const base =
typeof node.properties.class === 'string'
? node.properties.class
: '';
node.properties.class = cn(
base,
'code-block-line-highlight',
);
}
},
},
],
});
if (alive) setHtml(result);
} catch {
if (alive) setHtml(null);
}
})();
return () => {
alive = false;
};
// highlightKey 是 highlightLines 的稳定指纹,避免数组引用变化触发重算
}, [code, normalized, highlightKey]);
const handleCopy = () => {
void copy(code);
};
return (
<div
data-ai-component="code.block"
className={cn(
'overflow-hidden rounded-lg border border-content-border bg-content-bg-secondary',
className,
)}
{...props}
>
{filename !== undefined || copyable ? (
<div className="flex items-center justify-between gap-2 border-b border-content-border px-3 py-1.5">
<div className="flex min-w-0 items-center gap-2">
{filename !== undefined ? (
<span className="truncate text-2xs text-content-text-secondary">
{filename}
</span>
) : null}
<span className="shrink-0 text-2xs text-content-text-muted">
{language ?? text.code}
</span>
</div>
{copyable ? (
<Button
type="button"
variant="ghost"
size="icon-xs"
aria-label={copied ? text.copied : text.copy}
title={copied ? text.copied : text.copy}
onClick={handleCopy}
>
{copied ? (
<Check aria-hidden className="text-accent-green" />
) : (
<Copy aria-hidden />
)}
</Button>
) : null}
</div>
) : null}
<div
className={cn(
'overflow-auto',
showLineNumbers && 'code-block-line-numbers',
wrap && '[&_pre]:whitespace-pre-wrap [&_pre]:break-words',
)}
style={maxHeight !== undefined ? { maxHeight } : undefined}
>
{html ? (
<div
className="[&_pre]:m-0 [&_pre]:bg-transparent [&_pre]:p-3 [&_pre]:font-mono [&_pre]:text-xs [&_pre]:leading-relaxed"
dangerouslySetInnerHTML={{ __html: html }}
/>
) : (
<pre className="m-0 p-3 font-mono text-xs leading-relaxed whitespace-pre text-content-text">
<code>{code}</code>
</pre>
)}
</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/translatorprops,其次用I18nProvider目录;内置 zh-CN 默认值,en-US 为参考翻译。见Theming · i18n 与 RTL。 - 对比度:高对比度 token、2px 控件边框与 3px 焦点环由主题层统一提供,见Foundations · Contrast。
用法说明
代码展示件:Shiki 按需加载(首屏纯文本降级),主题走 CSS 变量随明暗切换;语言别名归一、未知语言降级 text;行号/高亮行由 data-line 驱动。shiki 为 optional peer,按子路径引入。