fix: 修复 Markdown 代码块渲染导致的 HTML hydration 错误

- 移除客户端状态管理,改为服务端渲染
- 添加 pre 组件处理代码块的包裹样式
- 修改 code 组件只返回 <code> 元素,避免重复渲染
- 添加 p 组件块级元素检测,防止 <p><pre> 嵌套
- 使用 className 和换行符检测区分 inline code 和代码块

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-12-28 10:32:49 +08:00
co-authored by Claude
parent bf69555978
commit a8a847beb2
+51 -47
View File
@@ -1,10 +1,8 @@
'use client' import React from 'react'
import ReactMarkdown from 'react-markdown' import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm' import remarkGfm from 'remark-gfm'
import rehypeRaw from 'rehype-raw' import rehypeRaw from 'rehype-raw'
import rehypeSanitize from 'rehype-sanitize' import rehypeSanitize from 'rehype-sanitize'
import { useState, useEffect } from 'react'
import type { Components } from 'react-markdown' import type { Components } from 'react-markdown'
interface MarkdownContentProps { interface MarkdownContentProps {
@@ -25,6 +23,14 @@ function generateHeadingId(text: string): string {
.replace(/-+$/, '') // Trim - from end .replace(/-+$/, '') // Trim - from end
} }
// Helper function to escape HTML
function escapeHtml(code: string): string {
return code
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
}
// Custom GitHub-style components // Custom GitHub-style components
const components: Components = { const components: Components = {
// Headings with anchor links // Headings with anchor links
@@ -81,12 +87,26 @@ const components: Components = {
</h4> </h4>
), ),
// Paragraphs // Paragraphs - skip wrapping if contains block-level elements like pre
p: ({ children, ...props }) => ( p: ({ children, node, ...props }: any) => {
<p className="mb-4 leading-7" {...props}> // Check if the paragraph node contains block-level elements in its children
{children} // This uses the AST node data from react-markdown
</p> const hasBlockElement = node?.children?.some((child: any) => {
), const tagName = child?.tagName
// Check if any direct child is a block-level element
return ['pre', 'table', 'blockquote', 'ul', 'ol', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'img', 'hr'].includes(tagName)
})
if (hasBlockElement) {
return <>{children}</>
}
return (
<p className="mb-4 leading-7" {...props}>
{children}
</p>
)
},
// Lists // Lists
ul: ({ children, className, ...props }) => ( ul: ({ children, className, ...props }) => (
@@ -111,9 +131,24 @@ const components: Components = {
</li> </li>
), ),
// Code blocks with syntax highlighting // Code blocks (pre element wrapper)
pre: ({ children, ...props }: any) => {
return (
<pre className="bg-gray-900 dark:bg-gray-950 text-gray-100 p-4 rounded-lg overflow-x-auto my-4 border border-gray-700" {...props}>
{children}
</pre>
)
},
// Code elements (both inline and in code blocks)
code: ({ inline, className, children, ...props }: any) => { code: ({ inline, className, children, ...props }: any) => {
if (inline) { // If inline is explicitly true, or if there's no language class and no newlines, treat as inline
const hasLanguageClass = className && typeof className === 'string' && className.startsWith('language-')
const childStr = String(children)
const hasNewlines = childStr.includes('\n')
const isInline = inline === true || (!hasLanguageClass && !hasNewlines)
if (isInline) {
return ( return (
<code <code
className="px-1.5 py-0.5 rounded bg-gray-100 dark:bg-gray-800 text-sm font-mono border border-gray-300 dark:border-gray-600" className="px-1.5 py-0.5 rounded bg-gray-100 dark:bg-gray-800 text-sm font-mono border border-gray-300 dark:border-gray-600"
@@ -124,10 +159,11 @@ const components: Components = {
) )
} }
const language = className?.replace(/language-/, '') || 'text' // For code blocks, just return the code element - the pre wrapper will be added by react-markdown
return ( return (
<SyntaxHighlighterWrapper language={language} code={String(children).trim()} /> <code className="text-sm font-mono" {...props}>
{children}
</code>
) )
}, },
@@ -202,44 +238,12 @@ const components: Components = {
checked={checked} checked={checked}
readOnly readOnly
className="mr-2 h-4 w-4 rounded border-gray-300" className="mr-2 h-4 w-4 rounded border-gray-300"
name="task-item"
{...props} {...props}
/> />
) : null, ) : null,
} }
// Syntax highlighter wrapper (will use Shiki for server-side, Prism for client)
function SyntaxHighlighterWrapper({ language, code }: { language: string; code: string }) {
const [highlighted, setHighlighted] = useState<string | null>(null)
useEffect(() => {
// For now, use simple highlighting with proper escaping
// In production, you'd want to use Shiki or Prism for better highlighting
const escaped = code
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
setHighlighted(escaped)
}, [code])
if (!highlighted) {
return (
<pre className="bg-gray-900 dark:bg-gray-950 text-gray-100 p-4 rounded-lg overflow-x-auto my-4 border border-gray-700">
<code className="text-sm font-mono">{code}</code>
</pre>
)
}
return (
<pre className="bg-gray-900 dark:bg-gray-950 text-gray-100 p-4 rounded-lg overflow-x-auto my-4 border border-gray-700">
<code
className="text-sm font-mono"
dangerouslySetInnerHTML={{ __html: highlighted }}
/>
</pre>
)
}
export function MarkdownContent({ content, className = '' }: MarkdownContentProps) { export function MarkdownContent({ content, className = '' }: MarkdownContentProps) {
if (!content || content.trim() === '') { if (!content || content.trim() === '') {