Code Block(代码块)
显示代码、终端输出和差异,可选择显示页头、行号及复制按钮。
CodeBlock 显示代码、终端输出、日志和差异。支持带标题和操作的页头、行号、换行、差异及行高亮,还提供用于在 Trace 中显示工具输出的小尺寸。
语法高亮是可选功能,由单独的 Hook 提供,因此只显示纯文本输出的代码块可以保持轻量。
安装
npx shadcn@latest add code-block1. 安装以下依赖:
npm install shiki2. 安装所需的 shadcn/ui 依赖:
npx shadcn@latest add button3. 将以下代码复制到你的项目中。
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
import { Button } from "./button"
import { CheckIcon, CopyIcon } from "lucide-react"
const codeBlockVariants = cva(
"group/code-block relative flex w-full min-w-0 flex-col overflow-hidden rounded-xl text-sm has-[>[data-slot=code-block-content]:focus-visible]:ring-[3px] has-[>[data-slot=code-block-content]:focus-visible]:ring-ring/50 data-[size=sm]:rounded-lg data-[size=sm]:text-xs",
{
variants: {
variant: {
default:
"border border-input bg-card text-card-foreground has-[>[data-slot=code-block-content]:focus-visible]:border-ring",
destructive:
"border border-destructive/30 text-destructive dark:border-destructive/40",
},
},
defaultVariants: {
variant: "default",
},
}
)
function CodeBlock({
className,
variant = "default",
size = "default",
...props
}: React.ComponentProps<"div"> &
VariantProps<typeof codeBlockVariants> & { size?: "default" | "sm" }) {
return (
<div
data-slot="code-block"
data-variant={variant}
data-size={size}
className={cn(codeBlockVariants({ variant }), className)}
{...props}
/>
)
}
function CodeBlockHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="code-block-header"
className={cn(
"flex min-w-0 shrink-0 items-center gap-2 px-4 pt-4 text-muted-foreground group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:pt-3 group-data-[variant=destructive]/code-block:text-destructive *:has-[>[data-slot=code-block-title]]:min-w-0",
className
)}
{...props}
/>
)
}
function CodeBlockTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="code-block-title"
className={cn(
"min-w-0 truncate font-sans text-sm font-medium text-foreground group-data-[size=sm]/code-block:text-xs group-data-[variant=destructive]/code-block:text-destructive [&_svg]:pointer-events-none [&_svg]:inline-block [&_svg]:align-middle [&_svg:not([class*='size-'])]:size-4 group-data-[size=sm]/code-block:[&_svg:not([class*='size-'])]:size-3.5 *:[svg]:me-1.5",
className
)}
{...props}
/>
)
}
function CodeBlockActions({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="code-block-actions"
className={cn(
"-my-1 ms-auto -me-1.5 flex shrink-0 items-center gap-1 [[data-slot=code-block]>&]:absolute [[data-slot=code-block]>&]:end-3 [[data-slot=code-block]>&]:top-3 [[data-slot=code-block]>&]:z-10 [[data-slot=code-block]>&]:m-0 [[data-slot=code-block]>&]:opacity-0 [[data-slot=code-block]>&]:transition-opacity [[data-slot=code-block]>&]:group-focus-within/code-block:opacity-100 [[data-slot=code-block]>&]:group-hover/code-block:opacity-100 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:end-2 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:top-2 [[data-slot=code-block]>&]:pointer-coarse:opacity-100 [[data-slot=code-block]>&]:*:[button]:bg-background [[data-slot=code-block]>&]:*:[button]:ring-1 [[data-slot=code-block]>&]:*:[button]:ring-foreground/10",
className
)}
{...props}
/>
)
}
function CodeBlockCopyButton({
value,
variant = "ghost",
size = "icon-xs",
className,
onClick,
...props
}: React.ComponentProps<typeof Button> & { value: string }) {
const [copied, setCopied] = React.useState(false)
React.useEffect(() => {
if (!copied) {
return
}
const timeout = setTimeout(() => setCopied(false), 2000)
return () => clearTimeout(timeout)
}, [copied])
return (
<>
<Button
data-slot="code-block-copy-button"
data-copied={copied || undefined}
variant={variant}
size={size}
aria-label={copied ? "Copied" : "Copy"}
className={cn(className)}
onClick={(event) => {
onClick?.(event)
navigator.clipboard
.writeText(value)
.then(() => setCopied(true))
.catch(() => {})
}}
{...props}
>
{copied ? (
<CheckIcon
/>
) : (
<CopyIcon
/>
)}
</Button>
<span aria-live="polite" className="sr-only">
{copied ? "Copied" : ""}
</span>
</>
)
}
function CodeBlockContent({
className,
children,
style,
wrap = false,
lineNumbers = false,
startLine = 1,
...props
}: React.ComponentProps<"pre"> & {
wrap?: boolean
lineNumbers?: boolean
startLine?: number
}) {
return (
<pre
data-slot="code-block-content"
data-wrap={wrap || undefined}
data-numbered={lineNumbers || undefined}
dir="ltr"
tabIndex={0}
style={{ counterReset: `line ${startLine - 1}`, ...style }}
className={cn(
"min-h-0 min-w-0 scroll-fade-x scrollbar-thin overflow-auto px-4 py-4 text-start type-code outline-none group-has-data-[slot=code-block-footer]/code-block:pb-2 group-has-data-[slot=code-block-header]/code-block:pt-2 group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:py-3 group-data-[size=sm]/code-block:group-has-data-[slot=code-block-header]/code-block:pt-1.5 data-wrap:scroll-fade-y data-wrap:wrap-break-word data-wrap:whitespace-pre-wrap",
className
)}
{...props}
>
<code
data-slot="code-block-code"
className="grid min-h-lh min-w-max content-start in-data-numbered:grid-cols-[auto_1fr] in-data-wrap:min-w-0"
>
{lineNumbers && typeof children === "string"
? children
.replace(/\n$/, "")
.split("\n")
.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))
: children}
</code>
</pre>
)
}
const codeBlockLineVariants = cva(
"relative -mx-4 block min-h-lh px-4 group-data-[size=sm]/code-block:-mx-3 group-data-[size=sm]/code-block:px-3 before:min-w-6 before:text-end before:text-muted-foreground after:absolute after:start-1 after:top-0 after:text-muted-foreground after:select-none in-data-numbered:col-span-2 in-data-numbered:grid in-data-numbered:grid-cols-subgrid in-data-numbered:gap-x-3 in-data-numbered:[counter-increment:line] in-data-numbered:before:content-[counter(line)] in-data-numbered:before:select-none in-data-numbered:supports-[content:counter(line)_/_'']:before:content-[counter(line)_/_'']",
{
variants: {
variant: {
default: "",
added: "bg-muted after:content-['+']",
removed: "bg-destructive/10 after:text-destructive after:content-['−']",
highlighted: "bg-muted",
},
},
defaultVariants: {
variant: "default",
},
}
)
function CodeBlockLine({
className,
variant = "default",
children,
...props
}: React.ComponentProps<"span"> & VariantProps<typeof codeBlockLineVariants>) {
// An empty line holds a newline so copying a selection keeps blank lines.
const empty =
children === undefined ||
children === null ||
children === "" ||
(Array.isArray(children) && children.length === 0)
return (
<span
data-slot="code-block-line"
data-variant={variant}
className={cn(codeBlockLineVariants({ variant }), className)}
{...props}
>
<span data-slot="code-block-line-content" className="min-w-0">
{empty ? "\n" : children}
</span>
</span>
)
}
function CodeBlockFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="code-block-footer"
className={cn(
"flex min-w-0 shrink-0 items-center gap-2 px-4 pb-4 text-muted-foreground group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:pb-3",
className
)}
{...props}
/>
)
}
export {
CodeBlock,
CodeBlockHeader,
CodeBlockTitle,
CodeBlockActions,
CodeBlockCopyButton,
CodeBlockContent,
CodeBlockLine,
CodeBlockFooter,
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import * as React from "react"
import { loadHighlighter } from "@/registry/bases/base/lib/highlighter"
export function useHighlightedCode(value: string, language: string) {
// A trailing newline would render as an extra empty line.
const code = value.endsWith("\n") ? value.slice(0, -1) : value
const [loaded, setLoaded] = React.useState<{
language: string
highlighter: Awaited<ReturnType<typeof loadHighlighter>>
} | null>(null)
const highlighter = loaded?.language === language ? loaded.highlighter : null
React.useEffect(() => {
let cancelled = false
loadHighlighter(language)
.then((next) => {
if (!cancelled) {
setLoaded({ language, highlighter: next })
}
})
.catch(() => {})
return () => {
cancelled = true
}
}, [language])
// The complete lines, highlighted. While the code streams, only the new
// lines are tokenized, starting from the grammar state of the last one.
const [done, setDone] = React.useState<{
highlighter: typeof highlighter
text: string
lines: React.ReactNode[]
state?: Parameters<NonNullable<typeof highlighter>["highlight"]>[1]
}>({ highlighter: null, text: "", lines: [] })
let next = done
if (next.highlighter !== highlighter || !code.startsWith(next.text)) {
next = { highlighter, text: "", lines: [] }
}
const end = code.lastIndexOf("\n") + 1
if (highlighter && end > next.text.length) {
const result = highlighter.highlight(
code.slice(next.text.length, end - 1),
next.state
)
next = {
highlighter,
text: code.slice(0, end),
lines: [...next.lines, ...result.lines],
state: result.state,
}
}
if (next !== done) {
setDone(next)
}
// The last line is still being written, so it is tokenized on every render.
const tail = code.slice(end)
return React.useMemo(() => {
if (!highlighter) {
return code.split("\n")
}
return [...next.lines, highlighter.highlight(tail, next.state).lines[0]]
}, [code, highlighter, next, tail])
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import * as React from "react"
import {
createHighlighterCore,
type GrammarState,
type HighlighterCore,
} from "shiki/core"
import { createJavaScriptRegexEngine } from "shiki/engine/javascript"
// Add the languages you need. Each one loads the first time it is used.
const languages = {
bash: () => import("shiki/langs/shellscript.mjs"),
css: () => import("shiki/langs/css.mjs"),
diff: () => import("shiki/langs/diff.mjs"),
html: () => import("shiki/langs/html.mjs"),
javascript: () => import("shiki/langs/javascript.mjs"),
json: () => import("shiki/langs/json.mjs"),
jsx: () => import("shiki/langs/jsx.mjs"),
markdown: () => import("shiki/langs/markdown.mjs"),
python: () => import("shiki/langs/python.mjs"),
sql: () => import("shiki/langs/sql.mjs"),
tsx: () => import("shiki/langs/tsx.mjs"),
typescript: () => import("shiki/langs/typescript.mjs"),
yaml: () => import("shiki/langs/yaml.mjs"),
}
const aliases: Record<string, keyof typeof languages> = {
js: "javascript",
md: "markdown",
py: "python",
sh: "bash",
shell: "bash",
shellscript: "bash",
ts: "typescript",
yml: "yaml",
zsh: "bash",
}
let highlighter: Promise<HighlighterCore> | undefined
function getHighlighter() {
highlighter ??= createHighlighterCore({
themes: [
import("shiki/themes/github-light.mjs"),
import("shiki/themes/github-dark.mjs"),
],
langs: [],
engine: createJavaScriptRegexEngine({ forgiving: true }),
})
return highlighter
}
function getLanguage(language: string) {
const name = language.toLowerCase()
if (name === "ansi") {
return name
}
if (name in languages) {
return name as keyof typeof languages
}
return aliases[name] ?? null
}
// Loads a language and returns a highlighter for it, or null for a language
// that is not listed.
export async function loadHighlighter(language: string) {
const lang = getLanguage(language)
if (!lang) {
return null
}
const shiki = await getHighlighter()
if (lang !== "ansi" && !shiki.getLoadedLanguages().includes(lang)) {
await shiki.loadLanguage(languages[lang])
}
return {
// Returns one React node per line, and the grammar state after the last
// line. Pass that state back to continue where the code left off.
highlight(code: string, state?: GrammarState) {
const tokenize = (text: string) =>
shiki.codeToTokens(text, {
lang,
themes: { light: "github-light", dark: "github-dark" },
defaultColor: false,
grammarState: state,
}).tokens
// ANSI has no grammar state, so each line is tokenized on its own and
// gets the same colors whether it arrives in one piece or streams.
const tokens =
lang === "ansi"
? code.split("\n").flatMap((line) => tokenize(line))
: tokenize(code)
return {
lines: tokens.map((line) =>
line.map((token, index) => (
<span
key={index}
style={token.htmlStyle as React.CSSProperties}
className="text-(--shiki-light) dark:text-(--shiki-dark)"
>
{token.content}
</span>
))
),
state: shiki.getLastGrammarState(tokens),
}
},
}
}
// Returns one React node per line, or null for a language that is not listed.
export async function highlightCode(code: string, language: string) {
const highlighter = await loadHighlighter(language)
return highlighter ? highlighter.highlight(code).lines : null
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
4. 根据你的项目配置调整导入路径。
code-block 还会安装用于语法高亮的 useHighlightedCode。
用法
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockFooter,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/components/ui/code-block"2
3
4
5
6
7
8
9
10
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>Terminal</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={output} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent>{output}</CodeBlockContent>
</CodeBlock>2
3
4
5
6
7
8
9
结构
CodeBlock
├── CodeBlockHeader
│ ├── CodeBlockTitle
│ └── CodeBlockActions
│ └── CodeBlockCopyButton
├── CodeBlockActions (floating, when there is no header)
├── CodeBlockContent
│ └── CodeBlockLine
└── CodeBlockFooter2
3
4
5
6
7
8
9
CodeBlockContent 接受字符串或一组 CodeBlockLine。需要行变体或语法高亮时,请使用 CodeBlockLine。
功能
- 流式输出的开销低。 字符串子项渲染为一个文本节点,流式接收代码时,高亮器只对新行分词。
- 复制结果干净。 行号和差异标记不会被选中,空行在复制时会保留。
- 从左到右阅读。 内容始终采用
dir="ltr",页头则遵循页面方向。 - 高亮无需 WASM。
useHighlightedCode使用 Shiki 的 JavaScript 引擎,在首次使用每种语言时加载它,并在终端输出中呈现 ANSI 颜色。服务端使用highlightCode可避免将 Shiki 打包进客户端。 - 适合各类代码场景。 可用于消息、Markdown 围栏、Trace 行、Tabs、Dialog 或
typeset容器。 - 支持键盘滚动。 内容可以聚焦,浮动操作既会在悬停时显示,也会在聚焦时显示。
基础
将字符串传给 CodeBlockContent。它渲染为一个文本节点,因此流式输出时开销较低。
页头
CodeBlockHeader 容纳 CodeBlockTitle 和 CodeBlockActions。CodeBlockCopyButton 复制它的 value。
过长的标题会截断。若要让标题链接到文件,请用链接元素包裹 CodeBlockTitle。
<CodeBlockHeader>
<a href="/files/route.ts">
<CodeBlockTitle>app/api/chat/route.ts</CodeBlockTitle>
</a>
</CodeBlockHeader>2
3
4
5
操作
CodeBlockActions 可容纳任意数量的按钮。若要提供换行开关,请自行管理状态并传给 wrap。
const [wrap, setWrap] = React.useState(false)
<CodeBlockActions>
<Button
variant="ghost"
size="icon-xs"
aria-label="Wrap lines"
aria-pressed={wrap}
onClick={() => setWrap(!wrap)}
>
<WrapTextIcon />
</Button>
<CodeBlockCopyButton value={output} />
</CodeBlockActions>
<CodeBlockContent wrap={wrap}>{output}</CodeBlockContent>2
3
4
5
6
7
8
9
10
11
12
13
14
15
浮动操作
没有页头时,可将 CodeBlockActions 直接放在 CodeBlock 内。操作浮动在顶部的末端,代码块悬停或聚焦时才显示。在触摸屏上始终显示。
行号
为 CodeBlockContent 添加 lineNumbers。字符串子项会拆成多行,选中内容复制时不包含行号。
起始行
使用 startLine 从指定行开始编号,适合展示文件中间的片段。行号栏会自动加宽,以容纳位数最多的行号。
换行
长行默认可横向滚动。添加 wrap 可换行显示,适合工具输出和错误消息。若要让读者切换换行设置,请参阅操作。
高亮行
将每行渲染为 CodeBlockLine,并在要强调的行上设置 variant="highlighted"。
差异
在 CodeBlockLine 上设置 variant="added" 或 variant="removed",分别添加 + 或 − 标记。
高度
使用 CodeBlockContent 上的 max-h-* 类限制高度,内容会在块内滚动。
滚动时,CodeBlockContent 会使用 scroll-fade 让边缘渐隐,默认为左右两侧,换行时为上下两侧。对于限高且不换行的代码块,可添加 scroll-fade-y。
显示更多
CodeBlockFooter 是内容下方的插槽。要实现「显示更多」,可在折叠时限制内容高度,并在页脚中放一个使用 ghost 变体的 xs 尺寸 Button。
const [expanded, setExpanded] = React.useState(false)
const id = React.useId()
<CodeBlockContent
id={id}
className={expanded ? undefined : "max-h-64 overflow-y-hidden scroll-fade-y"}
>
{code}
</CodeBlockContent>
<CodeBlockFooter className="justify-center">
<Button
variant="ghost"
size="xs"
aria-expanded={expanded}
aria-controls={id}
onClick={() => setExpanded(!expanded)}
>
{expanded ? "Show less" : "Show more"}
</Button>
</CodeBlockFooter>2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
最大高度
要避免长代码块占满页面,可以在展开时提高高度上限。展开的内容可滚动,边缘会随滚动渐隐。
尺寸
工具和 Trace 输出可使用 size="sm"。它使用更紧凑的内边距和 text-xs 文字。
危险操作
错误和失败输出使用 variant="destructive"。
Trace
在 TraceCollapsibleContent 中放置 size="sm" 的 CodeBlock,用于显示工具和终端输出。为 CodeBlockContent 添加 wrap 和 max-h-64 类,使长输出在 Trace 内换行并滚动。代码块自行设置文字颜色,因此 TraceCollapsibleContent 不会将其淡化。
标签页
用 Tabs 显示多个文件,在每个 TabsContent 中放一个 CodeBlock。
消息
将 CodeBlock 放在 Message 内的段落之间。
Typeset
CodeBlock 放入 typeset 容器后,会保留自身样式,上方间距与段落一致。
RTL
要在 shadcn/ui 中启用 RTL 支持,请参阅 RTL 配置指南。 Code always reads left to right. The header follows the page direction.
语法高亮
useHighlightedCode 使用 Shiki 高亮代码,为 CodeBlockLine 的每行返回一个 React 节点。
const lines = useHighlightedCode(code, "json")
<CodeBlock>
<CodeBlockContent>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>2
3
4
5
6
7
8
9
Shiki 使用 JavaScript 正则表达式引擎,因此无需加载 WASM。
语言
每种语言在首次使用时加载。可在 lib/highlighter.tsx 中编辑语言列表。列表以外的语言会按纯文本渲染。
默认列表包括 bash、css、diff、html、javascript、json、jsx、markdown、python、sql、tsx、typescript 和 yaml,以及 ts、js、sh 和 yml 等别名。
终端输出
将语言设为 "ansi",即可显示终端输出中的颜色。未设置时,转义码会显示为文本。
ANSI 颜色不会延续到下一行。
服务端渲染
highlightCode 是异步函数,可在服务端组件中使用,因此无需将 Shiki 打包进客户端。
import { highlightCode } from "@/lib/highlighter"
export async function ServerCode({ code }: { code: string }) {
const lines = (await highlightCode(code, "tsx")) ?? code.split("\n")
return (
<CodeBlock>
<CodeBlockContent lineNumbers>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>
)
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
流式输出
代码流式传输时,Hook 会从上次结束的行开始,只对新行分词。未更改的行保留原节点,因此 React 会跳过这些行。
Markdown
用 Streamdown 渲染消息,并通过 components.code 将围栏代码交给 CodeBlock 渲染。Streamdown 只为围栏代码设置 data-block,行内代码仍会在行内显示。
在收到闭合围栏之前,useIsCodeFenceIncomplete 会返回 true。用它在代码还不完整时禁用复制按钮。Streamdown 收到 isAnimating 时此 Hook 才会生效,因此请在消息流式传输期间传入 isAnimating。
<Streamdown components={{ code: MarkdownCode }} isAnimating={isStreaming}>
{text}
</Streamdown>2
3
无障碍
CodeBlockContent是包含code元素的pre,始终设置dir="ltr",因此在 RTL 页面上仍按从左到右的顺序阅读代码。CodeBlockContent设置了tabIndex={0},键盘用户可以聚焦并滚动。传入tabIndex={-1}可将其从 Tab 顺序中移除。- 焦点位于块内时也会显示浮动操作,因此键盘用户同样可以使用它们。
- 屏幕阅读器不会读出行号。
- 差异行除了着色,还带有
+或−标记,因此用户也能通过标记识别变更。 CodeBlockCopyButton的标签为「Copy」。复制成功后,礼貌级实时区域会播报「Copied」。- 为换行开关设置
aria-pressed,以便辅助技术播报它的状态。 - 为「显示更多」按钮设置
aria-expanded,并将aria-controls指向CodeBlockContent的id。
API 参考
CodeBlock
容纳页头、内容和页脚的容器。
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
variant | "default" | "destructive" | "default" | 代码块的视觉语气。 |
size | "default" | "sm" | "default" | "sm" 使用更紧凑的内边距和 text-xs 代码文字,适合工具输出。 |
className | string | - | 应用于代码块的附加类。 |
CodeBlockHeader
位于内容上方的一行,用于放置标题和操作。
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
className | string | - | 应用于页头的附加类。 |
CodeBlockTitle
文件名或标签,可选显示图标。过长时会截断。
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
className | string | - | 应用于标题的附加类。 |
CodeBlockActions
容纳页头末端的按钮。作为 CodeBlock 的直接子项时会浮动显示。
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
className | string | - | 应用于操作容器的附加类。 |
CodeBlockCopyButton
使用 ghost 变体的图标按钮,将 value 复制到剪贴板。它接受 Button 的属性。
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
value | string | - | 必填。要复制的文字。 |
className | string | - | 应用于按钮的附加类。 |
CodeBlockContent
支持滚动或换行的 pre。
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
children | React.ReactNode | - | 字符串或一组 CodeBlockLine。 |
wrap | boolean | false | 让过长的行换行显示。 |
lineNumbers | boolean | false | 为每行编号。字符串子项会按行拆分。 |
startLine | number | 1 | 设置 lineNumbers 时的第一行行号。 |
tabIndex | number | 0 | 让内容可以聚焦,以便用键盘滚动。 |
className | string | - | 应用于内容的附加类,例如 max-h-72。 |
CodeBlockLine
一行代码。
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
variant | "default" | "added" | "removed" | "highlighted" | "default" | 当前行的状态。 |
className | string | - | 应用于当前行的附加类。 |
CodeBlockFooter
位于内容下方的一行,例如用来放置「显示更多」按钮。
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
className | string | - | 应用于页脚的附加类。 |
useHighlightedCode
const lines = useHighlightedCode(code, language)每行返回一个 React 节点。在首次高亮处理完成前,以及语言不在列表中时,会返回纯文本行。
| 参数 | 类型 | 说明 |
|---|---|---|
code | string | 要高亮的代码。会忽略末尾的换行符。 |
language | string | lib/highlighter.tsx 中的语言或别名,也可使用 "ansi"。 |