Skip to content

feat: add extraCssVarPrefixCls option to inject CSS vars for additional prefix classes#36

Merged
zombieJ merged 7 commits intomasterfrom
feature/additional-prefix-cls
Feb 9, 2026
Merged

feat: add extraCssVarPrefixCls option to inject CSS vars for additional prefix classes#36
zombieJ merged 7 commits intomasterfrom
feature/additional-prefix-cls

Conversation

@zombieJ
Copy link
Member

@zombieJ zombieJ commented Feb 6, 2026

此特性在 genStyleUtils 中新增 extraCssVarPrefixCls 配置选项,用于为自定义 prefixCls 注入 CSS 变量。

设计背景

在组件库开发中,同一组件常存在多个变体(如 compact、large 等),这些变体需要共享基础组件的 CSS 变量,但不必重复注入样式逻辑。extraCssVarPrefixCls
旨在解耦样式注入与变量注册,为变体组件提供轻量级的 CSS 变量支持。

变更内容

  • API 新增:GenStyleUtilsOptions 类型新增 extraCssVarPrefixCls?: string[] 配置项
  • 实现逻辑:在 genStyleHooks 生成的 hook 中,遍历 extraCssVarPrefixCls 数组,为每个 prefixCls 调用 useCSSVar 进行变量注册

适用场景

  • 组件变体需继承基础组件的 CSS 变量(如紧凑模式、大尺寸模式)
  • 多个组件共享同一套 CSS 变量系统
  • 需隔离样式注入但复用变量定义的场景

Summary by CodeRabbit

发布说明

  • 新功能

    • 样式生成器新增 extraCssVarPrefixCls 选项,支持为多个自定义前缀类自动注册 CSS 变量。
  • 改进

    • 支持多根前缀注册(rootCls 可接受单值或数组),并在注册前对样式令牌做集中处理与映射以统一输出。
    • 若干类型与格式化细节微调(不改变行为)。
  • 测试

    • 新增验证额外前缀注入行为的测试,现有测试做了格式性调整。

…al prefix classes

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @zombieJ, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

此拉取请求引入了一个新功能,旨在优化组件库中 CSS 变量的管理。通过允许为组件的变体(如紧凑模式或大尺寸模式)注入共享的 CSS 变量,而无需重复的样式注入,它解耦了样式注入和变量注册过程。这使得组件变体能够轻量级地继承基础组件的样式系统,从而提高了代码的可维护性和复用性。

Highlights

  • 新增 extraCssVarPrefixCls 选项: 在 src/util/genStyleUtils.tsGenStyleUtilsOptions 类型中新增了 extraCssVarPrefixCls 选项,允许为自定义的 prefixCls 注入 CSS 变量。
  • CSS 变量注册逻辑增强: genStyleHooks 函数现在会遍历 extraCssVarPrefixCls 数组,并为每个 prefixCls 调用 useCSSVar 进行变量注册,而无需重复注入样式逻辑。
  • 新增测试用例: 在 tests/genStyleUtils.test.tsx 中新增了测试用例,以验证 extraCssVarPrefixCls 功能的正确性,确保 useCSSVarRegister 被正确调用。

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • src/util/genStyleUtils.ts
    • GenStyleUtilsOptions 类型中添加了 extraCssVarPrefixCls?: string[] 属性,用于指定需要额外注入 CSS 变量的 prefixCls
    • 修改了 genStyleHooks 函数,使其在生成 hook 时,遍历 options.extraCssVarPrefixCls 数组,并为每个自定义 prefixCls 调用 useCSSVar 进行 CSS 变量注册。
    • 调整了类型定义 GetResetStylesoptions 对象中的分号和换行符,以提高代码可读性。
  • tests/genStyleUtils.test.tsx
    • 模拟了 @ant-design/cssinjs 模块中的 useCSSVarRegister 函数,以便在测试中跟踪其调用。
    • beforeEach 钩子中添加了 jest.clearAllMocks(),确保每次测试前清除模拟函数的调用记录。
    • 新增了一个测试用例,验证当 extraCssVarPrefixCls 选项被提供时,useCSSVarRegister 会为根 prefixCls 和所有额外的 prefixCls 正确调用。
    • 调整了 getDefaultTokengenStyleUtils 调用中的分号,以符合代码风格。
Activity
  • 此拉取请求目前没有评论或审查活动。
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai
Copy link

coderabbitai bot commented Feb 6, 2026

Warning

Rate limit exceeded

@zombieJ has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 10 minutes and 1 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📝 Walkthrough

Walkthrough

为样式钩子生成器新增公共选项 extraCssVarPrefixCls?: string[],引入 tokenGenerator 到 CSS 变量注册流程以支持 token 重映射,并将生成器返回的 rootCls 类型扩展为 string | string[];新增与更新测试覆盖该行为。

Changes

Cohort / File(s) Summary
样式工具
src/util/genStyleUtils.ts
添加 extraCssVarPrefixCls?: string[]genStyleHooks 选项;引入并使用 tokenGenerator 用于 CSS 变量注册;当提供额外前缀时为每个前缀调用 useCSSVar;返回签名接受 `rootCls: string
新增测试
tests/extraCssVarPrefixCls.test.tsx
新增测试以验证当传入 extraCssVarPrefixCls(如 custom-a, custom-b)时,生成的样式包含对应前缀选择器与 CSS 变量注册。
现有测试更新
tests/genStyleUtils.test.tsx
对测试文件做细微格式化和语法调整(逗号/分号、泛型写法),测试逻辑保持不变。
文档/计划
action.md
记录对 useCSSVarRegister / serializeCSSVar 支持多 scope 的设计提议(影响序列化与注册策略)。
依赖
package.json
@ant-design/cssinjs 版本从 ^2.0.1 固定为 2.1.0

Sequence Diagram(s)

sequenceDiagram
  participant Dev as Developer
  participant Gen as genStyleUtils
  participant Hook as GeneratedHook
  participant CSS as useCSSVar
  participant DOM as StyleProvider/DOM

  Dev->>Gen: 调用 genStyleHooks(tokens, options{ extraCssVarPrefixCls })
  Gen-->>Dev: 返回 GeneratedHook
  Dev->>Hook: 在组件中调用 GeneratedHook
  Hook->>CSS: 调用 useCSSVar(rootCls)
  alt extraCssVarPrefixCls 存在
    Hook->>CSS: 对每个额外前缀调用 useCSSVar(e.g. custom-a, custom-b)
  end
  CSS->>DOM: 在样式区注册 CSS 变量 / 规则
  DOM->>Dev: 渲染时样式生效
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

庆祝诗

🐰 新增前缀入列忙,
变量跳队整队装。
测试轻敲真与详,
兔子欢跃拍掌藏。 🎉

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 标题清晰准确地总结了PR的主要变更:添加extraCssVarPrefixCls选项以为额外前缀类注入CSS变量。内容与改动完全对应,简洁明了。

✏️ 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 feature/additional-prefix-cls

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 Feb 6, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.26%. Comparing base (e968a8a) to head (2204e7c).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master      #36      +/-   ##
==========================================
+ Coverage   89.89%   90.26%   +0.36%     
==========================================
  Files          11       11              
  Lines         297      298       +1     
  Branches       74       71       -3     
==========================================
+ Hits          267      269       +2     
+ Misses         30       29       -1     

☔ 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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link

@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: 0

Caution

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

⚠️ Outside diff range comments (1)
src/util/genStyleUtils.ts (1)

213-222: ⚠️ Potential issue | 🟠 Major

forEach 循环中调用 React Hook 违反了 Hooks 规则。

useCSSVar 内部调用了 useToken()useCSSVarRegister(),这两个都是 React Hook。在 forEach 循环中调用它们违反了 React 的 Hooks 规则(不要在循环中调用 Hook),会触发 react-hooks/rules-of-hooks ESLint 规则报错。即使 extraCssVarPrefixCls 长度固定,循环调用 Hook 仍然是禁止的,因为 React 按调用顺序追踪 Hook 状态,循环模式违反了这一基本要求。

建议的解决方案有:

  1. 如果注册的 prefix 数量确实是固定的,显式编写每个 Hook 调用,避免循环。
  2. 如果数量动态,将 CSS 变量注册逻辑移入 genCSSVarRegister 内部,使其接收 prefix 列表参数,在单次 Hook 调用中完成所有注册。
  3. 或者创建一个封装组件来处理额外的 CSS 变量注册。

原建议中预先生成 Hook 数组并在 forEach 循环中调用的方案仍存在同样的问题。

🧹 Nitpick comments (1)
tests/genStyleUtils.test.tsx (1)

69-96: 测试用例逻辑正确,覆盖了新功能的核心场景。

测试验证了 extraCssVarPrefixCls: ['custom-a', 'custom-b'] 导致 useCSSVarRegister 被调用 3 次(test-prefixcustom-acustom-b),且每次调用的 scope 参数正确。

有一点需要注意:此测试因为 mock 了 useCSSVarRegister,所以不会触发 React 的 Rules of Hooks 校验。在实际使用中,forEach 内调用 hook 可能会引发问题(见 genStyleUtils.ts 的相关评论)。建议补充一个边界测试:extraCssVarPrefixCls 为空数组 [] 时,useCSSVarRegister 只被调用 1 次。

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request successfully introduces the extraCssVarPrefixCls option to genStyleUtils, allowing for the injection of CSS variables for additional prefix classes without injecting styles. This feature is well-implemented and addresses the described use case for component variants. The addition of a dedicated test case in tests/genStyleUtils.test.tsx to verify the useCSSVarRegister calls for these extra prefixes is excellent and ensures the new functionality works as expected. The code changes are clean and maintainable.

Copy link

@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: 3

🤖 Fix all issues with AI agents
In `@tests/extraCssVarPrefixCls.test.tsx`:
- Around line 70-72: The failing assertion expects the literal selector
".test-prefix" but the generated CSS may wrap selectors (e.g.,
:where(.test-prefix)) or omit the leading dot, and mocks may be incomplete so
CSS vars aren't emitted; update the test around totalStyle to assert against the
actual output by either matching without the leading dot or using a regex that
tolerates wrappers (reference totalStyle and the generated selector
"test-prefix"/":where(.test-prefix)"), and also verify the theme/mock used by
useCSSVar emits variables—enhance the mock if necessary so CSS variable
injection runs before asserting.
- Line 68: Remove the debug console.log in the test — delete the line that calls
console.log('Total CSS:', totalStyle) in tests/extraCssVarPrefixCls.test.tsx
(search for the console.log referencing totalStyle) so the test no longer emits
noisy output in CI; if you need retained information for assertions, replace it
with an appropriate expect(...) assertion using the totalStyle variable instead
of logging.
- Around line 43-51: The style generator callbacks passed to genStyleHooks (the
2nd and 3rd arguments) return empty objects causing the style-injection to be
skipped; update those callbacks in tests/extraCssVarPrefixCls.test.tsx to return
at least one minimal, valid CSS rule (e.g., a dummy class or an inherited
property) so the injectStyle flow creates the <style> for the `.test-prefix`
prefix and the extraCssVarPrefixCls behavior is exercised.

@zombieJ zombieJ force-pushed the feature/additional-prefix-cls branch from 40cd99a to aaf1869 Compare February 6, 2026 16:39
@zombieJ zombieJ force-pushed the feature/additional-prefix-cls branch from aaf1869 to 485b231 Compare February 6, 2026 16:41
- Update @ant-design/cssinjs to 2.1.0 which supports scope array
- Pass all scopes to single useCSSVarRegister call instead of looping
- Generates comma-separated selectors for better performance

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Copy link

@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

🤖 Fix all issues with AI agents
In `@package.json`:
- Line 60: The dependency entry "@ant-design/cssinjs": "2.1.0" in package.json
is invalid; update the version string to a valid published version such as
"2.0.3" or a semver range like "^2.0.3" to allow patch updates, then run npm
install to verify; ensure you change the value for the exact key
"@ant-design/cssinjs" in package.json and commit the updated package.json (and
package-lock.json/yarn.lock if present).
🧹 Nitpick comments (3)
action.md (1)

1-53: 规划文档,无阻塞性问题。

该文件为后续 @ant-design/cssinjs 的优化规划,不影响当前运行时行为。内容清晰,建议后续完成优化后删除或移至项目 wiki/issue 中,避免长期留存在代码仓库根目录。

src/util/genStyleUtils.ts (2)

242-263: tokenGenerator 每次渲染都会创建新的函数引用。

tokenGenerator 在 hook 体内定义为普通函数,每次渲染都会生成新引用。如果 useCSSVarRegister 内部对该回调做了引用比较(如 deps 比较或缓存 key),可能导致不必要的重复注册。建议确认 useCSSVarRegister 内部是否依赖该回调的引用稳定性;如果是,考虑用 useCallbackuseMemo 包裹。


213-220: options?.extraCssVarPrefixCls 未做空数组保护。

extraCssVarPrefixCls 为空数组 [] 时,条件判断为 truthy,会走数组分支传入 [rootCls],虽功能上不影响正确性(scope 变成单元素数组而非字符串),但与未传该选项时的行为不一致。建议加上长度检查:

建议的修改
-      const cssVarCls = useCSSVar(
-        options?.extraCssVarPrefixCls ? [rootCls, ...options.extraCssVarPrefixCls] : rootCls,
-      );
+      const cssVarCls = useCSSVar(
+        options?.extraCssVarPrefixCls?.length ? [rootCls, ...options.extraCssVarPrefixCls] : rootCls,
+      );

zombieJ and others added 2 commits February 9, 2026 14:59
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@zombieJ
Copy link
Member Author

zombieJ commented Feb 9, 2026

@gemini-code-assist, CR again

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

你好,感谢你的贡献。这个 PR 增加的 extraCssVarPrefixCls 选项是一个很实用的功能,能够很好地解决组件变体共享 CSS 变量的问题。整体实现思路清晰,并且添加了相应的单元测试来保证功能的正确性。我只发现了一个可以改进的小地方,主要是关于对空数组处理的一致性,已经在代码中提出了具体建议。请查看我的评论。

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@zombieJ zombieJ merged commit 88567ae into master Feb 9, 2026
7 of 8 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.

1 participant