refactor: receive nonce from parameters instead of StyleContext#253
refactor: receive nonce from parameters instead of StyleContext#253
Conversation
- Remove nonce field from StyleContextProps - Add nonce parameter to useCacheToken Option interface - Add nonce parameter to useCSSVarRegister config - Let hooks receive nonce explicitly from props/info/config Breaking: callers must now pass nonce explicitly to useCacheToken and useCSSVarRegister instead of relying on StyleContext propagation.
- Replace 'StyleProvider nonce for CSS var' test with 'useCacheToken with nonce parameter' - Tests now pass nonce explicitly to useCacheToken via its Option parameter - Tests cover both string and function nonce values
|
🎊 PR Preview 9b49a1c has been successfully built and deployed to https://ant-design-cssinjs-preview-pr-253.surge.sh 🕐 Build time: 87.742s 🤖 By surge-preview |
📝 Walkthrough走查本拉取请求将 nonce 配置从 StyleContext 层级重构至单个 Hook 层级。移除了 StyleContextProps 中的 nonce 属性,并在 useCSSVarRegister 和 useCacheToken 中添加了 nonce 选项,同时更新了相关测试以验证新的 nonce 传递机制。 更改
评审工作量估计🎯 2 (简单) | ⏱️ ~12 分钟 诗歌
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
Tip Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs). 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
tests/index.spec.tsx (1)
526-528: 建议:考虑添加无 nonce 时的负向测试用例。当前测试覆盖了
nonce为字符串和函数的情况。可以考虑添加一个测试用例,验证当不传递nonce参数时,生成的<style>元素不包含nonce属性,以确保默认行为的正确性。🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/index.spec.tsx` around lines 526 - 528, Add a negative test case that renders the styles without passing any nonce and asserts the produced <style> element does not include a nonce attribute; locate the existing style lookup (styles.find(s => s.innerHTML.includes('--primary-color')) as used in the snippet) and add an assertion like expecting cssVarStyle?.nonce to be undefined (or that the element does not have a nonce attribute) to verify default behavior when nonce is omitted.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/hooks/useCacheToken.tsx`:
- Line 70: The TypeScript error comes from placing nonce inside cssVar while the
code destructures nonce from the Option root; move the nonce property from the
cssVar object into the Option interface root so the type matches usage. Update
the Option type declaration to include nonce?: string | (() => string) at root
level (remove it from cssVar), and ensure any references or defaults that read
nonce (e.g., where options are destructured) still compile against the new
shape; adjust any tests or callers that passed nonce inside cssVar to pass it at
the Option root.
---
Nitpick comments:
In `@tests/index.spec.tsx`:
- Around line 526-528: Add a negative test case that renders the styles without
passing any nonce and asserts the produced <style> element does not include a
nonce attribute; locate the existing style lookup (styles.find(s =>
s.innerHTML.includes('--primary-color')) as used in the snippet) and add an
assertion like expecting cssVarStyle?.nonce to be undefined (or that the element
does not have a nonce attribute) to verify default behavior when nonce is
omitted.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: eb378860-0f8b-42fe-976b-eb5d5ea7d186
📒 Files selected for processing (4)
src/StyleContext.tsxsrc/hooks/useCSSVarRegister.tssrc/hooks/useCacheToken.tsxtests/index.spec.tsx
💤 Files with no reviewable changes (1)
- src/StyleContext.tsx
| preserve?: Record<string, boolean>; | ||
| /** Key for current theme. Useful for customizing and should be unique */ | ||
| key: string; | ||
| nonce?: string | (() => string); |
There was a problem hiding this comment.
类型定义与实现不一致导致编译失败。
nonce 被定义在 cssVar 对象内部(第 70 行),但在第 172 行代码尝试从 option 根级别解构 nonce。这导致了 pipeline 中的 TypeScript 错误:TS2339: Property 'nonce' does not exist on type 'Option'。
根据 PR 目标和测试用例的写法,nonce 应该放在 Option 接口的根级别,而不是嵌套在 cssVar 内。
🐛 建议修复:将 nonce 移至 Option 根级别
export interface Option<DerivativeToken, DesignToken> {
/**
* Generate token with salt.
* This is used to generate different hashId even same derivative token for different version.
*/
salt?: string;
override?: object;
+ /**
+ * CSP nonce for style injection.
+ */
+ nonce?: string | (() => string);
/**
* Format token as you need. Such as:
*
* - rename token
* - merge token
* - delete token
*
* This should always be the same since it's one time process.
* It's ok to useMemo outside but this has better cache strategy.
*/
formatToken?: (mergedToken: any) => DerivativeToken;
// ... other fields ...
/**
* Transform token to css variables.
*/
cssVar: {
hashed?: boolean;
/** Prefix for css variables */
prefix?: string;
/** Tokens that should not be appended with unit */
unitless?: Record<string, boolean>;
/** Tokens that should not be transformed to css variables */
ignore?: Record<string, boolean>;
/** Tokens that preserves origin value */
preserve?: Record<string, boolean>;
/** Key for current theme. Useful for customizing and should be unique */
key: string;
- nonce?: string | (() => string);
};
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/hooks/useCacheToken.tsx` at line 70, The TypeScript error comes from
placing nonce inside cssVar while the code destructures nonce from the Option
root; move the nonce property from the cssVar object into the Option interface
root so the type matches usage. Update the Option type declaration to include
nonce?: string | (() => string) at root level (remove it from cssVar), and
ensure any references or defaults that read nonce (e.g., where options are
destructured) still compile against the new shape; adjust any tests or callers
that passed nonce inside cssVar to pass it at the Option root.
Summary of ChangesHello, 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! This pull request introduces a significant refactoring of how Content Security Policy (CSP) nonces are managed within the CSS-in-JS library. The core change shifts nonce provision from an implicit context-based system to an explicit parameter-based approach for key hooks. This modification improves the clarity and control over nonce values, making the system more robust and easier to reason about, while also enhancing type safety for developers. Highlights
🧠 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
Activity
Using Gemini Code AssistThe 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
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 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
|
There was a problem hiding this comment.
Code Review
This pull request successfully refactors the nonce handling by moving it from StyleContext to explicit parameter passing in useCacheToken and useCSSVarRegister hooks. This change aligns with the stated goals of improving predictability, type safety, and flexibility. The tests have been appropriately updated to reflect the new API, ensuring the new behavior is correctly verified. The implementation is clean and directly addresses the described breaking change.

Summary
This PR refactors how nonce is passed to CSS-in-JS hooks by removing it from
StyleContextand requiring explicit parameter passing. This makes nonce handling more explicit and predictable.Changes
noncefield fromStyleContextPropsinterfacenonce?: string | (() => string)to theOptioninterfacenoncefrom theoptionparameter instead ofuseContext(StyleContext)nonce?: string | (() => string)to the config typenoncefrom theconfigparameter instead ofuseContext(StyleContext)Breaking Changes
Callers must now explicitly pass the
nonceparameter when using:useCacheToken- via theOptionparameteruseCSSVarRegister- via the config parameteruseStyleRegister(already supported parameter-based nonce - no change needed)The automatic propagation of
noncefromStyleProviderthrough the context is removed.Migration Example
Before:
After:
Testing
Motivation
Making nonce explicit improves:
Summary by CodeRabbit
发布说明