Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@Div627
Copy link
Contributor

@Div627 Div627 commented Jan 26, 2026

…loading

中文版模板 / Chinese template

🤔 This is a ...

  • 🆕 New feature
  • 🐞 Bug fix
  • 📝 Site / documentation improvement
  • 📽️ Demo improvement
  • 💄 Component style improvement
  • 🤖 TypeScript definition improvement
  • 📦 Bundle size optimization
  • ⚡️ Performance optimization
  • ⭐️ Feature enhancement
  • 🌐 Internationalization
  • 🛠 Refactoring
  • 🎨 Code style optimization
  • ✅ Test Case
  • 🔀 Branch merge
  • ⏩ Workflow
  • ⌨️ Accessibility improvement
  • ❓ Other (about what?)

🔗 Related Issues

  • Describe the source of related requirements, such as links to relevant issue discussions.
  • For example: close #xxxx, fix #xxxx

💡 Background and Solution

  • The specific problem to be addressed.
  • List the final API implementation and usage if needed.
  • If there are UI/interaction changes, consider providing screenshots or GIFs.

📝 Change Log

Language Changelog
🇺🇸 English CodeHighlighter: Add usePrismLight prop (default: false); CodeHighlighter: Implement dynamic language loading with cache; CodeHighlighter: Add Suspense boundary for async loading; Mermaid: Replace SyntaxHighlighter with CodeHighlighter; Tests: Update mocks for new component structure.
🇨🇳 Chinese CodeHighlighter: 新增 usePrismLight 属性(默认: false);CodeHighlighter: 实现带缓存的语言动态加载;CodeHighlighter: 添加 Suspense 边界处理异步加载;Mermaid: 使用 CodeHighlighter 替换 SyntaxHighlighter;测试: 更新 mock 以适配新组件结构。

Summary by CodeRabbit

  • 新功能
    • 新增 prismLightMode 配置(默认开启),支持按需延迟加载语言高亮以减小初始包体积。
  • 改进
    • 优化代码高亮渲染流程与容错(无 children 返回 null、无 lang 返回原生 code、Suspense 支持等),替换内部高亮实现并统一 Mermaid 渲染路径。
  • 文档
    • 更新中英文示例与属性表,新增 prismLightMode 说明与示例。
  • 测试
    • 扩充针对 prismLightMode、渲染行为和边界情况的单元测试。

✏️ Tip: You can customize this high-level summary in your review settings.

@github-actions
Copy link
Contributor

github-actions bot commented Jan 26, 2026

Preview failed

@dosubot dosubot bot added the enhancement New feature or request label Jan 26, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 26, 2026

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

  • 🔍 Trigger a full review
📝 Walkthrough

Walkthrough

为 CodeHighlighter 引入基于 prismLightMode 的按需 Prism 语言懒加载,重构渲染流程以支持 Suspense 回退,并在 Mermaid 中将代码渲染替换为 CodeHighlighter;同步更新接口、示例与测试以覆盖新行为。

Changes

Cohort / File(s) 变更摘要
CodeHighlighter 实现
packages/x/components/code-highlighter/CodeHighlighter.tsx
新增 per-language 缓存与全量高亮器缓存,添加 getAsyncHighlightergetFullPrismHighlighter,引入 lazy/Suspense,新增 prismLightMode?: boolean 属性,按需加载 Prism 语言,高亮渲染改为可 Suspense 包裹,增加空 children / 无 lang 早期返回逻辑。
接口声明
packages/x/components/code-highlighter/interface.ts
CodeHighlighterProps 中新增可选 prismLightMode?: boolean(文档注释与默认值说明)。
Mermaid 组件
packages/x/components/mermaid/Mermaid.tsx
将原有 SyntaxHighlighter 渲染路径替换为 CodeHighlighter;更新 MermaidProps.highlightProps 类型为 CodeHighlighterProps['highlightProps'],并调整传入的 header、样式与高亮参数。
CodeHighlighter 测试
packages/x/components/code-highlighter/__tests__/index.test.tsx
扩展测试覆盖 prismLightMode(默认/禁用)、header/headerTitle/样式/className、Suspense 回退、无 lang 路径、特殊输入与行尾空行处理、ref 转发、displayName、data-* 透传等多种场景;引入异步断言(waitFor)。
Mermaid 测试
packages/x/components/mermaid/__tests__/index.test.tsx
将对 SyntaxHighlighter 的 mock 替换为 CodeHighlighter mock,mock 支持可选 header prop 并在测试中适配输出。
示例与文档
packages/x/components/code-highlighter/demo/basic.tsx, .../index.en-US.md, .../index.zh-CN.md
demo 中新增 Prism Light Mode 示例;中/英文文档新增 prismLightMode 属性说明(默认 true)。

Sequence Diagram(s)

sequenceDiagram
    participant App as 上层组件
    participant CH as CodeHighlighter
    participant Lazy as React.lazy
    participant Prism as Prism (语言模块)
    participant Susp as Suspense/Fallback

    App->>CH: 渲染 (prismLightMode=true, lang=jsx)
    alt 指定 lang 且 prismLightMode=true
        CH->>Lazy: 请求/创建 AsyncHighlighter
        Lazy->>Prism: 动态导入 prism- jsx 模块
        par 加载中
            CH->>Susp: 返回 Suspense 回退(或纯 <code>)
        and 加载完成
            Prism-->>Lazy: 语言模块加载完成
            Lazy->>CH: AsyncHighlighter 可用
            CH->>App: 渲染带高亮的代码节点
        end
    else prismLightMode=false 或 未指定 lang
        CH->>App: 直接使用全量高亮器或返回纯 <code>
    end
Loading

Estimated code review effort

🎯 4 (复杂) | ⏱️ ~45 分钟

庆贺诗

🐰 轻载代码随风来,
悬念解开有回退,
Mermaid 换裙显新彩,
懒加载步履不慌,
花园里跃动高亮光。

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed PR标题清晰准确地概括了主要变更:通过按需语言加载实现性能优化和减少打包体积,与原始摘要中的核心改动完全一致。
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 unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch build/codehight-build

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.

@codecov
Copy link

codecov bot commented Jan 26, 2026

Bundle Report

Changes will decrease total bundle size by 2.54MB (-55.52%) ⬇️. This is within the configured threshold ✅

Detailed changes
Bundle name Size Change
x-markdown-array-push 119.31kB -1.49MB (-92.61%) ⬇️
antdx-array-push 1.92MB -1.05MB (-35.36%) ⬇️

Affected Assets, Files, and Routes:

view changes for bundle: x-markdown-array-push

Assets Changed:

Asset Name Size Change Total Size Change (%)
x-markdown.min.js (New) 112.95kB 112.95kB 100.0% 🚀
x-markdown.min.css (New) 6.36kB 6.36kB 100.0% 🚀
latex.js (Deleted) -513.05kB 0 bytes -100.0% 🗑️
static/KaTeX_AMS-Regular.*.ttf (Deleted) -63.63kB 0 bytes -100.0% 🗑️
static/KaTeX_Main-Regular.*.ttf (Deleted) -53.58kB 0 bytes -100.0% 🗑️
static/KaTeX_Main-Bold.*.ttf (Deleted) -51.34kB 0 bytes -100.0% 🗑️
static/KaTeX_Main-Italic.*.ttf (Deleted) -33.58kB 0 bytes -100.0% 🗑️
static/KaTeX_AMS-Regular.*.woff (Deleted) -33.52kB 0 bytes -100.0% 🗑️
static/KaTeX_Main-BoldItalic.*.ttf (Deleted) -32.97kB 0 bytes -100.0% 🗑️
static/KaTeX_Math-Italic.*.ttf (Deleted) -31.31kB 0 bytes -100.0% 🗑️
static/KaTeX_Math-BoldItalic.*.ttf (Deleted) -31.2kB 0 bytes -100.0% 🗑️
static/KaTeX_Main-Regular.*.woff (Deleted) -30.77kB 0 bytes -100.0% 🗑️
static/KaTeX_Main-Bold.*.woff (Deleted) -29.91kB 0 bytes -100.0% 🗑️
static/KaTeX_AMS-Regular.*.woff2 (Deleted) -28.08kB 0 bytes -100.0% 🗑️
static/KaTeX_Typewriter-Regular.*.ttf (Deleted) -27.56kB 0 bytes -100.0% 🗑️
static/KaTeX_Main-Regular.*.woff2 (Deleted) -26.27kB 0 bytes -100.0% 🗑️
static/KaTeX_Main-Bold.*.woff2 (Deleted) -25.32kB 0 bytes -100.0% 🗑️
static/KaTeX_SansSerif-Bold.*.ttf (Deleted) -24.5kB 0 bytes -100.0% 🗑️
latex.css (Deleted) -24.32kB 0 bytes -100.0% 🗑️
static/KaTeX_SansSerif-Italic.*.ttf (Deleted) -22.36kB 0 bytes -100.0% 🗑️
static/KaTeX_Main-Italic.*.woff (Deleted) -19.68kB 0 bytes -100.0% 🗑️
static/KaTeX_Fraktur-Bold.*.ttf (Deleted) -19.58kB 0 bytes -100.0% 🗑️
static/KaTeX_Fraktur-Regular.*.ttf (Deleted) -19.57kB 0 bytes -100.0% 🗑️
static/KaTeX_SansSerif-Regular.*.ttf (Deleted) -19.44kB 0 bytes -100.0% 🗑️
static/KaTeX_Main-BoldItalic.*.woff (Deleted) -19.41kB 0 bytes -100.0% 🗑️
static/KaTeX_Math-Italic.*.woff (Deleted) -18.75kB 0 bytes -100.0% 🗑️
static/KaTeX_Math-BoldItalic.*.woff (Deleted) -18.67kB 0 bytes -100.0% 🗑️
static/KaTeX_Main-Italic.*.woff2 (Deleted) -16.99kB 0 bytes -100.0% 🗑️
static/KaTeX_Main-BoldItalic.*.woff2 (Deleted) -16.78kB 0 bytes -100.0% 🗑️
static/KaTeX_Script-Regular.*.ttf (Deleted) -16.65kB 0 bytes -100.0% 🗑️
static/KaTeX_Math-Italic.*.woff2 (Deleted) -16.44kB 0 bytes -100.0% 🗑️
static/KaTeX_Math-BoldItalic.*.woff2 (Deleted) -16.4kB 0 bytes -100.0% 🗑️
static/KaTeX_Typewriter-Regular.*.woff (Deleted) -16.03kB 0 bytes -100.0% 🗑️
static/KaTeX_SansSerif-Bold.*.woff (Deleted) -14.41kB 0 bytes -100.0% 🗑️
static/KaTeX_SansSerif-Italic.*.woff (Deleted) -14.11kB 0 bytes -100.0% 🗑️
static/KaTeX_Typewriter-Regular.*.woff2 (Deleted) -13.57kB 0 bytes -100.0% 🗑️
static/KaTeX_Fraktur-Bold.*.woff (Deleted) -13.3kB 0 bytes -100.0% 🗑️
static/KaTeX_Fraktur-Regular.*.woff (Deleted) -13.21kB 0 bytes -100.0% 🗑️
static/KaTeX_Caligraphic-Bold.*.ttf (Deleted) -12.37kB 0 bytes -100.0% 🗑️
static/KaTeX_Caligraphic-Regular.*.ttf (Deleted) -12.34kB 0 bytes -100.0% 🗑️
static/KaTeX_SansSerif-Regular.*.woff (Deleted) -12.32kB 0 bytes -100.0% 🗑️
static/KaTeX_Size1-Regular.*.ttf (Deleted) -12.23kB 0 bytes -100.0% 🗑️
static/KaTeX_SansSerif-Bold.*.woff2 (Deleted) -12.22kB 0 bytes -100.0% 🗑️
static/KaTeX_SansSerif-Italic.*.woff2 (Deleted) -12.03kB 0 bytes -100.0% 🗑️
static/KaTeX_Size2-Regular.*.ttf (Deleted) -11.51kB 0 bytes -100.0% 🗑️
static/KaTeX_Fraktur-Bold.*.woff2 (Deleted) -11.35kB 0 bytes -100.0% 🗑️
static/KaTeX_Fraktur-Regular.*.woff2 (Deleted) -11.32kB 0 bytes -100.0% 🗑️
static/KaTeX_Script-Regular.*.woff (Deleted) -10.59kB 0 bytes -100.0% 🗑️
static/KaTeX_Size4-Regular.*.ttf (Deleted) -10.36kB 0 bytes -100.0% 🗑️
static/KaTeX_SansSerif-Regular.*.woff2 (Deleted) -10.34kB 0 bytes -100.0% 🗑️
static/KaTeX_Script-Regular.*.woff2 (Deleted) -9.64kB 0 bytes -100.0% 🗑️
static/KaTeX_Caligraphic-Bold.*.woff (Deleted) -7.72kB 0 bytes -100.0% 🗑️
static/KaTeX_Caligraphic-Regular.*.woff (Deleted) -7.66kB 0 bytes -100.0% 🗑️
static/KaTeX_Size3-Regular.*.ttf (Deleted) -7.59kB 0 bytes -100.0% 🗑️
static/KaTeX_Caligraphic-Bold.*.woff2 (Deleted) -6.91kB 0 bytes -100.0% 🗑️
static/KaTeX_Caligraphic-Regular.*.woff2 (Deleted) -6.91kB 0 bytes -100.0% 🗑️
static/KaTeX_Size1-Regular.*.woff (Deleted) -6.5kB 0 bytes -100.0% 🗑️
static/KaTeX_Size2-Regular.*.woff (Deleted) -6.19kB 0 bytes -100.0% 🗑️
static/KaTeX_Size4-Regular.*.woff (Deleted) -5.98kB 0 bytes -100.0% 🗑️
static/KaTeX_Size1-Regular.*.woff2 (Deleted) -5.47kB 0 bytes -100.0% 🗑️
static/KaTeX_Size2-Regular.*.woff2 (Deleted) -5.21kB 0 bytes -100.0% 🗑️
static/KaTeX_Size4-Regular.*.woff2 (Deleted) -4.93kB 0 bytes -100.0% 🗑️
static/KaTeX_Size3-Regular.*.woff (Deleted) -4.42kB 0 bytes -100.0% 🗑️
static/KaTeX_Size3-Regular.*.woff2 (Deleted) -3.62kB 0 bytes -100.0% 🗑️
view changes for bundle: antdx-array-push

Assets Changed:

Asset Name Size Change Total Size Change (%)
antdx.min.js (New) 1.92MB 1.92MB 100.0% 🚀
antdx.js (Deleted) -2.97MB 0 bytes -100.0% 🗑️

@Div627 Div627 linked an issue Jan 26, 2026 that may be closed by this pull request
@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Jan 26, 2026

Deploying ant-design-x with  Cloudflare Pages  Cloudflare Pages

Latest commit: eafb277
Status: ✅  Deploy successful!
Preview URL: https://5d83b9a0.ant-design-x.pages.dev
Branch Preview URL: https://build-codehight-build.ant-design-x.pages.dev

View logs

@codecov
Copy link

codecov bot commented Jan 26, 2026

Codecov Report

❌ Patch coverage is 96.96970% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 97.32%. Comparing base (3d9a75f) to head (eafb277).
⚠️ Report is 13 commits behind head on feature.

Files with missing lines Patch % Lines
.../x/components/code-highlighter/CodeHighlighter.tsx 96.96% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           feature    #1691      +/-   ##
===========================================
- Coverage    97.32%   97.32%   -0.01%     
===========================================
  Files          144      144              
  Lines         4568     4597      +29     
  Branches      1264     1277      +13     
===========================================
+ Hits          4446     4474      +28     
- Misses         120      121       +1     
  Partials         2        2              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@github-actions
Copy link
Contributor

github-actions bot commented Jan 26, 2026

size-limit report 📦

Path Size
packages/x/dist/antdx.min.js 461.41 KB (+7.98 KB 🔺)
packages/x-sdk/dist/x-sdk.min.js 7.88 KB
packages/x-markdown/dist/x-markdown.min.js 30.99 KB (-51 B 🔽)
packages/x-markdown/dist/plugins/latex.min.js 61.95 KB

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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)
packages/x/components/code-highlighter/CodeHighlighter.tsx (1)

2-75: 应改用 PrismAsyncLight 并调用 loadLanguage() 实现真正的按需加载

当前实现有两处致命问题:

  1. 第 3 行的全量 Prism 导入 — 仍然会把所有语言打包进去,无法减包。
  2. 第 51 行的动态导入未生效 — 从 prismjs/components 导入的模块没有注册到 react-syntax-highlighter,语言定义未被识别。

正确的做法是改用 PrismAsyncLight(或 PrismLight),并调用官方的 loadLanguage(lang) API,同时从正确的路径 react-syntax-highlighter/dist/esm/languages/prism/<language> 导入语言模块。这样才能真正实现代码分割和按需加载。

🤖 Fix all issues with AI agents
In `@packages/x/components/code-highlighter/CodeHighlighter.tsx`:
- Around line 77-85: The component currently returns a bare <code> when lang is
missing, skipping the outer wrapper/header/language title/copy button; instead,
default lang to 'plaintext' and let the normal render path run so the outer
container and controls remain consistent. Concretely, in the CodeHighlighter
component replace the early-return for falsy lang (but keep the early-return for
no children) by assigning a fallback like const effectiveLang = lang ||
'plaintext' (or similar) and use effectiveLang in the existing
highlighting/render logic so header, language label and copy button (the same
elements used when lang is present) are still rendered.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@packages/x/components/code-highlighter/CodeHighlighter.tsx`:
- Around line 41-75: The current logic creates a new React.lazy component inside
useMemo whenever lang changes, causing remounts and losing lazy caching; move
lazy creation to a module-level cache (e.g., Map<string, LazyComponent>) keyed
by lang and create the lazy AsyncSyntaxHighlighter only once per language (use a
cached entry for subsequent renders), then have useMemo simply select either the
cached lazy component (when prismLightMode && lang) or the regular
SyntaxHighlighter; keep the same fallback behavior (returning a component that
renders <SyntaxHighlighter language={lang} PreTag="div" />) and reference the
existing symbols AsyncHighlighter, AsyncSyntaxHighlighter, SyntaxHighlighter,
lang, and prismLightMode when implementing the cache.
- Line 51: The dynamic import using import(`prismjs/components/prism-${lang}`)
in CodeHighlighter (the langModule load) creates an unsafe context import that
pulls all prism language modules; update the implementation to constrain
bundlers: either switch to a webpack-friendly dynamic import with magic comments
and explicit .js extension (replace the template import of prism-${lang} with a
webpackInclude/webpackChunkName variant), or refactor to use import.meta.glob to
pre-declare prismjs/components/prism-*.js and load from that map at runtime, or
replace the dynamic import with a static mapping of language name → loader
function; modify the code that assigns langModule to load via the chosen
constrained approach so bundlers only include needed files.
♻️ Duplicate comments (1)
packages/x/components/code-highlighter/CodeHighlighter.tsx (1)

82-85: lang 为空时返回裸 <code> 元素的问题已在之前的评审中指出

此问题已被标记,建议使用 plaintext 作为默认语言以保持一致的组件结构。

🧹 Nitpick comments (1)
packages/x/components/code-highlighter/__tests__/index.test.tsx (1)

115-124: 建议使用异步测试工具验证 Suspense 行为

当前测试是同步的,但 prismLightMode 启用时组件使用 Suspense 进行异步加载。虽然测试可能因 fallback 内容而通过,但无法验证实际的异步加载流程。

建议使用 waitForfindBy* 查询来验证异步行为:

♻️ 建议的改进
+import { render, waitFor } from '@testing-library/react';
+
 describe('prismLightMode', () => {
-  it('should render code with prismLightMode enabled', () => {
+  it('should render code with prismLightMode enabled', async () => {
     const { container } = render(
       <CodeHighlighter lang="javascript" prismLightMode>
         {`console.log("test");`}
       </CodeHighlighter>,
     );
-    expect(container.querySelector('code')).toBeInTheDocument();
-    expect(container.textContent).toContain('console.log("test");');
+    // Verify fallback is shown initially
+    expect(container.textContent).toContain('console.log("test");');
+    
+    // Wait for async loading to complete
+    await waitFor(() => {
+      expect(container.querySelector('pre')).toBeInTheDocument();
+    });
   });

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@packages/x/components/code-highlighter/__tests__/index.test.tsx`:
- Around line 388-400: The RTL test currently only sets data-direction on
CodeHighlighter; update the test in index.test.tsx to mock or wrap with the
XProviderContext (or XProvider) and set direction='rtl' so the component
receives real context-based RTL; then assert that the rendered element
(querySelector('.ant-codeHighlighter')) contains the RTL class (e.g.
'.ant-codeHighlighter-rtl') and/or appropriate RTL attributes to confirm
behavior; target the test block named 'should render with RTL direction' and the
CodeHighlighter component to implement this change.
- Around line 351-361: The test description and assertions are wrong because
CodeHighlighter returns early when lang=="" (see CodeHighlighter early return at
lines ~95-97), so either change the test to assert the early-return behavior
(expect a bare <code> render) or modify the test inputs to actually trigger
FullPrismHighlighter; e.g., call render(<CodeHighlighter lang="js"
prismLightMode={false}>...) or omit the lang prop/use undefined so the component
proceeds to load FullPrismHighlighter, and update the it(...) description
accordingly to match the new expectation.
🧹 Nitpick comments (1)
packages/x/components/code-highlighter/CodeHighlighter.tsx (1)

80-87: 存在未使用的代码路径。

prismLightMode=truelang 为空时,第 86 行会将 SyntaxHighlighter 赋值给 Highlighter,但第 95-97 行的 early return 会在使用前退出。考虑将 early return 移到 Highlighter 赋值之前,或添加注释说明此行为。

♻️ 建议的重构方案
+  // ============================ Early Returns ============================
+  if (!children) {
+    return null;
+  }
+
+  // No lang means no highlighting needed, return plain code directly
+  if (!lang) {
+    return <code>{children}</code>;
+  }
+
   // Get the appropriate highlighter component
   // - prismLightMode = true (default): Use PrismLight with async language loading
   // - prismLightMode = false: Use full Prism (all languages included)
-  const Highlighter = prismLightMode
-    ? lang
-      ? getAsyncHighlighter(lang)
-      : SyntaxHighlighter
-    : getFullPrismHighlighter();
-
-  // ============================ Early Returns ============================
-  if (!children) {
-    return null;
-  }
-
-  // No lang means no highlighting needed, return plain code directly
-  if (!lang) {
-    return <code>{children}</code>;
-  }
+  const Highlighter = prismLightMode
+    ? getAsyncHighlighter(lang)
+    : getFullPrismHighlighter();

Comment on lines 351 to 361
it('should use FullPrismHighlighter when prismLightMode=false and no lang', async () => {
const { container } = render(
<CodeHighlighter lang="" prismLightMode={false}>
{`plain code`}
</CodeHighlighter>,
);
// Should use full Prism with Suspense fallback
await waitFor(() => {
expect(container.textContent).toContain('plain code');
});
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

测试用例与实际行为不符。

lang="" 时,组件在第 95-97 行会 early return 返回裸 <code> 元素,不会使用 FullPrismHighlighter。此测试实际上测试的是 early return 行为,而非 FullPrismHighlighter 的加载。测试描述与实际行为不匹配。

💚 建议的修复
-    it('should use FullPrismHighlighter when prismLightMode=false and no lang', async () => {
+    it('should render plain code when no lang (early return before FullPrismHighlighter)', async () => {
       const { container } = render(
         <CodeHighlighter lang="" prismLightMode={false}>
           {`plain code`}
         </CodeHighlighter>,
       );
-      // Should use full Prism with Suspense fallback
+      // Should early return with plain <code> element (no highlighting)
       await waitFor(() => {
         expect(container.textContent).toContain('plain code');
       });
+      // Verify it's the early return path (bare code element)
+      expect(container.querySelector('.ant-codeHighlighter')).toBeNull();
     });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it('should use FullPrismHighlighter when prismLightMode=false and no lang', async () => {
const { container } = render(
<CodeHighlighter lang="" prismLightMode={false}>
{`plain code`}
</CodeHighlighter>,
);
// Should use full Prism with Suspense fallback
await waitFor(() => {
expect(container.textContent).toContain('plain code');
});
});
it('should render plain code when no lang (early return before FullPrismHighlighter)', async () => {
const { container } = render(
<CodeHighlighter lang="" prismLightMode={false}>
{`plain code`}
</CodeHighlighter>,
);
// Should early return with plain <code> element (no highlighting)
await waitFor(() => {
expect(container.textContent).toContain('plain code');
});
// Verify it's the early return path (bare code element)
expect(container.querySelector('.ant-codeHighlighter')).toBeNull();
});
🤖 Prompt for AI Agents
In `@packages/x/components/code-highlighter/__tests__/index.test.tsx` around lines
351 - 361, The test description and assertions are wrong because CodeHighlighter
returns early when lang=="" (see CodeHighlighter early return at lines ~95-97),
so either change the test to assert the early-return behavior (expect a bare
<code> render) or modify the test inputs to actually trigger
FullPrismHighlighter; e.g., call render(<CodeHighlighter lang="js"
prismLightMode={false}>...) or omit the lang prop/use undefined so the component
proceeds to load FullPrismHighlighter, and update the it(...) description
accordingly to match the new expectation.

Comment on lines +388 to +400
describe('RTL support', () => {
it('should render with RTL direction', async () => {
// Mock XProvider context with RTL direction
const { container } = render(
<CodeHighlighter lang="javascript" data-direction="rtl">
{`console.log("test");`}
</CodeHighlighter>,
);
await waitFor(() => {
expect(container.querySelector('.ant-codeHighlighter')).toBeInTheDocument();
});
});
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

RTL 测试未验证实际的 RTL 功能。

当前测试只传递了 data-direction="rtl" 属性(通过 restProps),但未验证组件是否应用了 RTL 样式类(如 .ant-codeHighlighter-rtl)。需要 mock XProviderContext 来设置 direction='rtl' 才能测试真正的 RTL 行为。

💚 建议的改进
 describe('RTL support', () => {
-    it('should render with RTL direction', async () => {
-      // Mock XProvider context with RTL direction
-      const { container } = render(
-        <CodeHighlighter lang="javascript" data-direction="rtl">
-          {`console.log("test");`}
-        </CodeHighlighter>,
-      );
-      await waitFor(() => {
-        expect(container.querySelector('.ant-codeHighlighter')).toBeInTheDocument();
-      });
-    });
+    // TODO: Add proper RTL test by mocking XProviderContext with direction='rtl'
+    // and verifying .ant-codeHighlighter-rtl class is applied
+    it('should render component without RTL context', async () => {
+      const { container } = render(
+        <CodeHighlighter lang="javascript">
+          {`console.log("test");`}
+        </CodeHighlighter>,
+      );
+      await waitFor(() => {
+        expect(container.querySelector('.ant-codeHighlighter')).toBeInTheDocument();
+      });
+      // Without RTL context, should not have RTL class
+      expect(container.querySelector('.ant-codeHighlighter-rtl')).toBeNull();
+    });
 });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
describe('RTL support', () => {
it('should render with RTL direction', async () => {
// Mock XProvider context with RTL direction
const { container } = render(
<CodeHighlighter lang="javascript" data-direction="rtl">
{`console.log("test");`}
</CodeHighlighter>,
);
await waitFor(() => {
expect(container.querySelector('.ant-codeHighlighter')).toBeInTheDocument();
});
});
});
describe('RTL support', () => {
// TODO: Add proper RTL test by mocking XProviderContext with direction='rtl'
// and verifying .ant-codeHighlighter-rtl class is applied
it('should render component without RTL context', async () => {
const { container } = render(
<CodeHighlighter lang="javascript">
{`console.log("test");`}
</CodeHighlighter>,
);
await waitFor(() => {
expect(container.querySelector('.ant-codeHighlighter')).toBeInTheDocument();
});
// Without RTL context, should not have RTL class
expect(container.querySelector('.ant-codeHighlighter-rtl')).toBeNull();
});
});
🤖 Prompt for AI Agents
In `@packages/x/components/code-highlighter/__tests__/index.test.tsx` around lines
388 - 400, The RTL test currently only sets data-direction on CodeHighlighter;
update the test in index.test.tsx to mock or wrap with the XProviderContext (or
XProvider) and set direction='rtl' so the component receives real context-based
RTL; then assert that the rendered element
(querySelector('.ant-codeHighlighter')) contains the RTL class (e.g.
'.ant-codeHighlighter-rtl') and/or appropriate RTL attributes to confirm
behavior; target the test block named 'should render with RTL direction' and the
CodeHighlighter component to implement this change.

@Div627 Div627 changed the base branch from main to feature January 27, 2026 08:47
@github-actions
Copy link
Contributor

⚠️ Performance benchmark report not found.


This comment is automatically generated by the x-markdown performance CI.

@github-actions
Copy link
Contributor

⚠️ Performance benchmark report not found.


This comment is automatically generated by the x-markdown performance CI.

1 similar comment
@github-actions
Copy link
Contributor

⚠️ Performance benchmark report not found.


This comment is automatically generated by the x-markdown performance CI.

@github-actions
Copy link
Contributor

⚠️ Performance benchmark report not found.


This comment is automatically generated by the x-markdown performance CI.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CodeHighlighter 支持更灵活的配置

2 participants