Skip to content

fix: 改进 Markdown 代码块渲染 (#206)#210

Merged
AmintaCCCP merged 3 commits into
mainfrom
fix/markdown-code-block-rendering
Jun 7, 2026
Merged

fix: 改进 Markdown 代码块渲染 (#206)#210
AmintaCCCP merged 3 commits into
mainfrom
fix/markdown-code-block-rendering

Conversation

@AmintaCCCP

@AmintaCCCP AmintaCCCP commented Jun 7, 2026

Copy link
Copy Markdown
Owner

问题描述

修复 Issue #206 报告的 Markdown 代码块渲染问题:

  1. 反引号符号错误渲染
  2. 多行代码块发生换行,破坏代码布局

根本原因

问题 1:行内代码 vs 代码块判断错误

  • 原逻辑:仅通过 !className 判断是否为行内代码
  • 问题:没有语言标注的代码块(如 ```\ncode\n```)也没有 className,会被误判为行内代码
  • 结果:代码块被渲染成行内代码样式,反引号可能显示异常

问题 2:CSS 样式未明确禁止换行

  • 问题:没有显式设置 white-space: pre 等属性
  • 结果:某些情况下浏览器可能对代码进行换行

问题 3:翻译模式下的代码标签匹配不完整

  • 原逻辑:使用 /<code>([\s\S]*?)<\/code>/g 匹配
  • 问题:只能匹配不带属性的 <code> 标签
  • 结果:带属性的代码标签在翻译后可能丢失

实施的修复

修复 1:改进行内代码 vs 代码块判断逻辑

文件src/components/MarkdownRenderer.tsx

  • pre 组件给其子 code 元素添加 data-code-block 属性
  • code 组件通过检查该属性或 className 来判断是否为代码块
  • 即使没有语言标注的代码块也能正确识别

修复 2:增强代码块 CSS 样式

文件src/index.css

  • 添加 white-space: pre 保留空白字符,不折行
  • 添加 word-wrap: normalword-break: normal 防止单词断行
  • 添加 overflow-x: auto 提供横向滚动条
  • 确保代码块保持原始布局,不会因窗口宽度而换行

修复 3:修复翻译模式下的代码标签匹配

文件src/components/BilingualMarkdownRenderer.tsx

  • 修改正则表达式为 /<code(?:\s+[^>]*)?>([\s\S]*?)<\/code>/g
  • 现在可以正确匹配 <code><code class="..."><code data-code-block>
  • 翻译后的代码标签不会丢失

测试建议

  1. 测试有语言标注的代码块
  2. 测试无语言标注的代码块
  3. 测试行内代码
  4. 测试长代码行是否有横向滚动条而不是换行
  5. 测试翻译模式下代码是否正常显示
  6. 在用户提供的示例仓库中验证:

修改的文件

  • src/index.css - 增强代码块 CSS 样式
  • src/components/MarkdownRenderer.tsx - 改进代码块判断逻辑
  • src/components/BilingualMarkdownRenderer.tsx - 修复翻译模式代码匹配

兼容性说明

  • ✅ 所有修改都是向后兼容的
  • ✅ 不影响现有功能
  • ✅ 只是增强了边缘情况的处理

Closes #206

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • More reliable detection of inline vs. block code so code renders in the correct style.
    • Improved support for styled inline code (e.g., with attributes) so formatting displays correctly.
  • Style

    • Code blocks now allow horizontal scrolling and preserve preformatted layout.
    • Refined visual styling for standalone preformatted blocks to improve readability.

- Fix inline code vs code block detection logic
  * Add data-code-block marker from pre to code element
  * Support code blocks without language specification
  * Prevent misidentification of code blocks as inline code

- Enhance code block CSS styles to prevent line wrapping
  * Add white-space: pre to maintain original layout
  * Add word-wrap: normal and word-break: normal
  * Ensure horizontal scrolling instead of wrapping

- Fix code tag regex in translation mode
  * Support code tags with attributes like <code class="...">
  * Improve regex pattern to match all code tag variations

Fixes #206

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jun 7, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5d2f6cd3-9fd8-4cf9-897b-5c9e8ff65912

📥 Commits

Reviewing files that changed from the base of the PR and between c277a2e and 8ae59e9.

📒 Files selected for processing (1)
  • src/components/MarkdownRenderer.tsx

📝 Walkthrough

Walkthrough

Improves inline vs block code detection in MarkdownRenderer, relaxes BilingualMarkdownRenderer's code-tag regex to match code tags with attributes, and adds CSS to preserve preformatted layout and enable horizontal scrolling for long code lines.

Changes

Code Rendering Fix

Layer / File(s) Summary
Code block detection and marking
src/components/MarkdownRenderer.tsx
The code renderer now computes isCodeBlock from a data-code-block prop or className; pre clones child code elements and injects data-code-block: true to mark block context.
Bilingual translation regex update
src/components/BilingualMarkdownRenderer.tsx
The translation splitting regex for extracting <code> tags is made permissive so it matches <code> elements that include attributes (e.g., class="...").
Code block layout and overflow styling
src/index.css
Adds .prose pre and .prose pre code rules to enforce white-space: pre, disable wrapping/word-break, and enable horizontal scrolling; adds styles for pre:not(:has(code)) (and dark variant).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 I nudged the backticks into tidy arrays,
Inline and block now follow their ways,
Regex widened its curious eyes,
CSS whispers "scroll" to long code lines,
A hop, a fix — the renderer smiles.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Title is in Chinese and translates to 'fix: Improve Markdown code block rendering', directly addressing the main objective of fixing code block rendering issues referenced in Issue #206.
Linked Issues check ✅ Passed All four coding requirements from Issue #206 are met: backtick symbols no longer render, multi-line code blocks preserve formatting with horizontal scroll, inline vs block code is correctly distinguished via data-code-block attribute, and code tags with attributes are matched in bilingual mode.
Out of Scope Changes check ✅ Passed All changes directly address Issue #206 requirements: MarkdownRenderer fixes code block detection, CSS adds preformatted styling for code blocks, and BilingualMarkdownRenderer updates regex to handle code tags with attributes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/markdown-code-block-rendering

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/index.css (1)

194-213: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Replace deprecated word-wrap with overflow-wrap.

The word-wrap property is deprecated. Use overflow-wrap instead, which is the standard property name.

🔧 Proposed fix
  .prose pre {
    overflow-x: auto;
    white-space: pre;
-    word-wrap: normal;
+    overflow-wrap: normal;
    word-break: normal;
  }

  .prose pre code {
    display: block;
    padding: 1rem;
    border-radius: 0.5rem;
    font-size: 0.875rem;
    line-height: 1.5rem;
    tab-size: 2;
    -moz-tab-size: 2;
    white-space: pre;
-    word-wrap: normal;
+    overflow-wrap: normal;
    word-break: normal;
    overflow-x: auto;
  }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/index.css` around lines 194 - 213, Replace the deprecated CSS property
`word-wrap` with the standard `overflow-wrap` in both selectors; update the
rules in the `.prose pre` and `.prose pre code` blocks to remove `word-wrap:
normal;` and add `overflow-wrap: normal;` (keeping the other properties like
`white-space`, `word-break`, and `overflow-x` unchanged) so the styling uses the
modern property name.

Source: Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/components/MarkdownRenderer.tsx`:
- Around line 879-885: The pre renderer in MarkdownRenderer.tsx currently uses
React.cloneElement(children as React.ReactElement<any>, ...) which weakens type
safety; change the cast to a specific element prop type such as
React.ReactElement<React.ComponentPropsWithoutRef<'code'>> (or another
appropriate HTML/code prop type) so cloneElement's props are correctly typed and
the 'data-code-block' attribute is applied with proper typing for the children
element.

---

Outside diff comments:
In `@src/index.css`:
- Around line 194-213: Replace the deprecated CSS property `word-wrap` with the
standard `overflow-wrap` in both selectors; update the rules in the `.prose pre`
and `.prose pre code` blocks to remove `word-wrap: normal;` and add
`overflow-wrap: normal;` (keeping the other properties like `white-space`,
`word-break`, and `overflow-x` unchanged) so the styling uses the modern
property name.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5793cd81-7c47-4466-b1d9-2911274ef9ff

📥 Commits

Reviewing files that changed from the base of the PR and between fb9d2d1 and e2e458f.

📒 Files selected for processing (3)
  • src/components/BilingualMarkdownRenderer.tsx
  • src/components/MarkdownRenderer.tsx
  • src/index.css

Comment thread src/components/MarkdownRenderer.tsx
AmintaCCCP and others added 2 commits June 7, 2026 21:17
- Replace deprecated word-wrap with overflow-wrap in CSS
- Improve TypeScript type safety for React.cloneElement
- Add styling for plain pre tags (ASCII art/character art)
  * Support pre tags without code child elements
  * Ensure proper display for character art and diagrams
  * Maintain white-space: pre to prevent line wrapping

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Keep pre tag when it doesn't contain code child element
- Ensure ASCII art and character diagrams maintain their container
- Previously the pre tag was stripped causing layout issues

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@AmintaCCCP AmintaCCCP merged commit 6356798 into main Jun 7, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Markdown代码渲染问题

1 participant