JGuang

代码块

CodeBlock · Astryx

交互预览
npm install @astryxdesign/core@0.7.1 @astryxdesign/theme-neutral@0.7.1 @stylexjs/stylex@0.19.0

代码块 · CodeBlock

展示代码、语法主题及相关操作。

安装与前置条件

npm install @astryxdesign/core@0.7.1 @astryxdesign/theme-neutral@0.7.1 @stylexjs/stylex@0.19.0

需要 React 19+,按顺序导入基础 CSS 和主题,并设置 Theme Provider。参见开始使用。

示例与使用方式

  • 代码块 · 综合展示 1:首先体验这个示例,再查看代码理解组件的组合方式。
  • 代码块 · 交互示例 2:可交互查看这一用法的行为,复制代码时保留它实际使用的属性与导入。
  • 代码块 · 交互示例 3:可交互查看这一用法的行为,复制代码时保留它实际使用的属性与导入。
  • 代码块 · 交互示例 4:可交互查看这一用法的行为,复制代码时保留它实际使用的属性与导入。
  • 代码块 · 滚动 5:可交互查看这一用法的行为,复制代码时保留它实际使用的属性与导入。
  • 代码块 · 交互示例 6:可交互查看这一用法的行为,复制代码时保留它实际使用的属性与导入。

API 与上游详细参考

优先使用 0.7.1 官方中文说明;上游尚未提供中文的条目保留英文。属性名、类型及默认值保持原生 API,不把示例状态名称当成组件属性。

Code Block

CodeBlock displays syntax-highlighted code snippets with optional line numbers, copy button, and collapsible sections. Use CodeBlock for fenced multi-line code and Code for inline code within prose.

属性类型默认值说明
code *stringThe code string to display.
languagestring'plaintext'Language for syntax highlighting. Use "plaintext" to disable.
titlestringFilename or label shown in the header bar.
hasLanguageLabelbooleantrueShow the language name in the header bar. Hidden when language is "plaintext".
hasLineNumbersbooleanfalseShow a line number gutter.
highlightLinesnumber[]1-indexed line numbers to highlight.
isDiffbooleanfalseRender the code as a unified diff over language: lines starting with + are added, - removed, @@ is a hunk header (a --- /+++ file-header pair directly before one is a header too), anything else is context. The language label reads diff or <language> diff. The glyph sits in its own column and the rest of each line keeps syntax highlighting; copy returns the exact source. Markdown diff and diff-<lang> fences set this.
hasCopyButtonbooleantrueShow a copy-to-clipboard button.
onCopy() => voidCallback after the code is copied.
isWrappedbooleanfalseWrap long lines instead of enabling horizontal scroll.
maxHeightnumber | stringMax height before the block scrolls vertically.
size'sm' | 'md''md'Text size variant.
widthstring'fit-content'Width of the code block. Any CSS width value. 'fit-content' (default) shrinks to longest line. '100%' fills parent width.
container'card' | 'section''card'Container presentation style. 'card' (default): border and radius with the muted syntax background for a standalone card look. 'section': no border or radius and a transparent background so the block blends into the card or panel it's embedded in.
tokenizer(code: string, language: string) => Array<{type: string; start: number; end: number}>Custom tokenizer override for unsupported languages.
syntaxThemeSyntaxThemeDefinitionPer-instance syntax theme override. Shorthand for wrapping the block in <SyntaxTheme theme={...}>. Accepts a preset from @astryxdesign/core/theme/syntax or a theme created with defineSyntaxTheme(). Defaults to the nearest SyntaxTheme ancestor or the theme-level syntax colors.
highlightMode'auto' | 'ranges' | 'spans''auto'Syntax highlighting rendering mode.
isCollapsiblebooleanfalseAllow collapsing the code body into just the header bar. Starts expanded; a visible header becomes clickable when the code exceeds collapsibleThreshold lines. Headerless blocks never collapse, and removing the header expands a previously collapsed block.
collapsibleThresholdnumber10Minimum number of lines before the collapse toggle appears. Below this threshold the code block renders normally even when isCollapsible is true.
refReact.Ref<HTMLPreElement>Ref forwarded to the root code-block element.
xstyleStyleXStylesStyleX styles for layout customization. Must be a stylex.create() value.
classNamestringCSS class name for the root element. Prefer xstyle for styling.
styleCSSPropertiesInline styles. Prefer xstyle for StyleX-optimized styling.
data-testidstringTest selector for automated testing frameworks.

使用建议

  • Set the language prop to enable syntax highlighting. Use "plaintext" when the language is unknown or not supported.
  • Use Code for short inline code references within body text, and CodeBlock for standalone multi-line snippets.
  • 避免:Enable line numbers for short snippets where they add visual noise without aiding comprehension.
  • 避免:Wrap code blocks in a scrollable container when isWrapped or maxHeight already handles overflow.

主题 API

{
  "targets": [
    {
      "className": "astryx-code-block",
      "visualProps": [
        "size",
        "language",
        "container"
      ]
    },
    {
      "className": "astryx-code-block-header",
      "visualProps": [
        "size",
        "language",
        "container"
      ]
    },
    {
      "className": "astryx-code-block-title",
      "visualProps": [
        "size",
        "language"
      ]
    },
    {
      "className": "astryx-code-block-copy-button"
    }
  ],
  "vars": [
    {
      "name": "--_codeblock-gutter-width",
      "description": "Width of the line-number gutter, computed from the digit count of the last line so the code column starts at a stable offset.",
      "default": "2ch",
      "private": true
    }
  ]
}

Code

组件结构

  • Header Bar: Shows the title, visible language label, and copy button when a header is present. A title or visible language label creates the header; the copy button alone floats at the top-end of a headerless block.
  • Header Title: Groups the optional title, visible language label, and collapsible chevron inside the header bar.
  • Line Numbers: Numbered gutter along the left edge. Enable with hasLineNumbers.
  • Code Body: The syntax-highlighted code content.
  • Highlighted Lines: Background accent on specific lines to draw attention.
  • Copy Button: Copies the code string to the clipboard. Shown by default.