Skip to content

refactor: receive nonce from parameters instead of StyleContext#253

Closed
zombieJ wants to merge 2 commits intomasterfrom
refactor/nounce-parameter
Closed

refactor: receive nonce from parameters instead of StyleContext#253
zombieJ wants to merge 2 commits intomasterfrom
refactor/nounce-parameter

Conversation

@zombieJ
Copy link
Member

@zombieJ zombieJ commented Mar 4, 2026

Summary

This PR refactors how nonce is passed to CSS-in-JS hooks by removing it from StyleContext and requiring explicit parameter passing. This makes nonce handling more explicit and predictable.

Changes

  • StyleContext.tsx: Removed nonce field from StyleContextProps interface
  • useCacheToken.tsx:
    • Added nonce?: string | (() => string) to the Option interface
    • Hooks now receive nonce from the option parameter instead of useContext(StyleContext)
  • useCSSVarRegister.ts:
    • Added nonce?: string | (() => string) to the config type
    • Hooks now receive nonce from the config parameter instead of useContext(StyleContext)
  • tests/index.spec.tsx: Updated nonce tests to reflect the new API

Breaking Changes

⚠️ This is a breaking change.

Callers must now explicitly pass the nonce parameter when using:

  • useCacheToken - via the Option parameter
  • useCSSVarRegister - via the config parameter
  • useStyleRegister (already supported parameter-based nonce - no change needed)

The automatic propagation of nonce from StyleProvider through the context is removed.

Migration Example

Before:

function MyComponent() {
  const [token] = useCacheToken(theme, [baseToken], {
    cssVar: { key: 'css-var-test' }
  });
  // nonce was implicitly taken from StyleProvider
}

After:

function MyComponent() {
  const [token] = useCacheToken(theme, [baseToken], {
    cssVar: { key: 'css-var-test' },
    nonce: 'my-nonce'  // or nonce: () => 'my-nonce'
  });
}

Testing

  • All existing tests pass (161 passed, 1 skipped)
  • Updated nonce tests to use the new parameter-based API
  • Both string and function nonce values are tested

Motivation

Making nonce explicit improves:

  1. Predictability: nonce flow is clear from the code
  2. Type Safety: Type-checking catches missing nonce parameters
  3. Flexibility: Different components can use different nonces

Summary by CodeRabbit

发布说明

  • API 变更
    • 从样式提供者 API 中移除了全局 nonce 选项
    • CSS 变量配置现可在单个级别指定 nonce,提供更灵活的内容安全策略支持

zombieJ added 2 commits March 4, 2026 23:16
- 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
@github-actions
Copy link

github-actions bot commented Mar 4, 2026

🎊 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

@coderabbitai
Copy link

coderabbitai bot commented Mar 4, 2026

📝 Walkthrough

走查

本拉取请求将 nonce 配置从 StyleContext 层级重构至单个 Hook 层级。移除了 StyleContextProps 中的 nonce 属性,并在 useCSSVarRegister 和 useCacheToken 中添加了 nonce 选项,同时更新了相关测试以验证新的 nonce 传递机制。

更改

内聚组 / 文件 总结
StyleContext 属性移除
src/StyleContext.tsx
从 StyleContextProps 接口中移除公开的 nonce 属性,不再通过 StyleContext 提供 CSP nonce 功能。
Hook 层级 Nonce 支持
src/hooks/useCSSVarRegister.ts, src/hooks/useCacheToken.tsx
在 useCSSVarRegister 和 useCacheToken 的配置对象中添加 nonce 可选字段,并将其传递至 mergeCSSConfig 以支持样式更新时的 nonce 处理。
测试用例更新
tests/index.spec.tsx
用验证通过 useCacheToken 直接传递 nonce 的测试替换原有的 StyleProvider nonce 测试,覆盖字符串和函数两种 nonce 形式。

评审工作量估计

🎯 2 (简单) | ⏱️ ~12 分钟

诗歌

🐰 Nonce 迁移春风来,
从上下文流向 Hook 怀,
样式安全更精细,
配置灵活展新彩!✨

🚥 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 的主要变更:将 nonce 的来源从 StyleContext 改为参数传递。
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/nounce-parameter

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


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.

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

🧹 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

📥 Commits

Reviewing files that changed from the base of the PR and between 0d105b2 and 9b49a1c.

📒 Files selected for processing (4)
  • src/StyleContext.tsx
  • src/hooks/useCSSVarRegister.ts
  • src/hooks/useCacheToken.tsx
  • tests/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);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

类型定义与实现不一致导致编译失败。

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.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, 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

  • Nonce Handling Refactor: The mechanism for passing Content Security Policy (CSP) nonces to CSS-in-JS hooks has been refactored. Nonces are now explicitly passed as parameters to useCacheToken and useCSSVarRegister hooks, replacing the previous implicit propagation via StyleContext.
  • Breaking Change: This is a breaking change. Consumers of the library must now explicitly provide the nonce parameter when utilizing useCacheToken (via the Option parameter) and useCSSVarRegister (via the config parameter). The automatic propagation of nonce from StyleProvider through the context is no longer supported.
  • Improved Predictability and Type Safety: The change aims to enhance the predictability of nonce flow and improve type safety, allowing type-checking to identify missing nonce parameters at compile time. This also offers greater flexibility, enabling different components to use distinct nonces.

🧠 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/StyleContext.tsx
    • Removed the nonce field from the StyleContextProps interface, eliminating context-based nonce propagation.
  • src/hooks/useCSSVarRegister.ts
    • Added an optional nonce property to the configuration object for the useCSSVarRegister hook.
    • Modified the hook to retrieve the nonce value directly from its config parameter instead of the StyleContext.
  • src/hooks/useCacheToken.tsx
    • Added an optional nonce property to the Option interface within the useCacheToken hook, specifically for cssVar configurations.
    • Updated the useCacheToken hook to obtain the nonce value from its option parameter, removing its dependency on StyleContext.
  • tests/index.spec.tsx
    • Updated existing nonce tests for useCacheToken to align with the new parameter-based API.
    • Introduced new test cases to verify the correct application of nonce when provided as both a string and a function parameter.
Activity
  • The pull request was created by zombieJ to refactor nonce handling, making it explicit rather than context-dependent.
  • An auto-generated summary by CodeRabbit was added, highlighting API changes and the removal of the global nonce option from the style provider, and noting that CSS variable configuration now supports single-level nonce specification for flexible CSP.
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.

@zombieJ zombieJ closed this Mar 4, 2026
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 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.

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