Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: cascade layer is not applied when there is no style content #207

Merged
merged 2 commits into from
Dec 4, 2024

Conversation

Wxh16144
Copy link
Member

@Wxh16144 Wxh16144 commented Dec 4, 2024

fix: ant-design/ant-design#51867

Solution

antd 的某些组件,比如 popover 用的 tooltips, 设置了 injectStyle 为 false, 使得 useStyleRegister 放回空样式, stylis 处理后结果刚好碰到 thysultan/stylis#339 处理逻辑。导致多拼接了一个级联层。

Summary by CodeRabbit

  • 新功能

    • 增强了样式注册逻辑,确保在提供层时不会生成空的层样式。
  • 测试

    • 在样式注册测试中添加了新的测试用例,以验证当样式注册函数返回空数组时的行为。

Copy link

coderabbitai bot commented Dec 4, 2024

📝 Walkthrough

Walkthrough

此拉取请求对useStyleRegister模块中的parseStyle函数进行了修改,添加了条件检查以确保在提供layer时,只有在styleStr非空的情况下才会将其包裹在@layer指令中。此外,在tests/layer.spec.tsx中新增了一个测试用例,验证当样式注册函数返回空数组时的行为,确保生成的样式元素为空。

Changes

文件路径 更改摘要
src/hooks/useStyleRegister.tsx parseStyle函数中添加条件检查,确保只有在styleStr非空时才会使用@layer指令。
tests/layer.spec.tsx 新增测试用例empty braces (#51867),验证当样式注册返回空数组时的行为。

Assessment against linked issues

Objective Addressed Explanation
确保在样式注册时不生成空的@layer antd(#51867)
验证当样式注册返回空数组时的行为(#51867)

Possibly related issues

Possibly related PRs

Poem

🐰 在层中舞动的风,
样式不再空洞,
兔子欢快地跳,
让CSS更美好!
代码如画,风景如梦,
祝贺更改,心中有光! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Dec 4, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 94.88%. Comparing base (880ed09) to head (cfe8309).
Report is 7 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #207      +/-   ##
==========================================
- Coverage   95.07%   94.88%   -0.20%     
==========================================
  Files          33       33              
  Lines        2883     2891       +8     
  Branches      456      456              
==========================================
+ Hits         2741     2743       +2     
- Misses        142      148       +6     

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

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

🧹 Outside diff range and nitpick comments (3)
tests/layer.spec.tsx (1)

73-98: 测试用例设计合理且完整

测试用例很好地覆盖了当 style 注册返回空数组时的场景:

  1. 正确设置了 layer 配置
  2. 验证了生成的样式元素为空
  3. 直接针对 #51867 issue 中报告的问题

建议添加以下测试场景以提高覆盖率:

  it('empty braces (#51867)', () => {
    const theme = createTheme(() => ({}));
+   // 测试多个空样式的情况
+   const styles = [];
+   for (let i = 0; i < 3; i++) {
      const Demo = () => {
        useStyleRegister(
          {
            theme,
            token: { _tokenKey: 'test' },
            path: ['shared'],
            layer: {
              name: 'shared',
            },
          },
          () => [],
        );
        return null;
      };

      render(
        <StyleProvider layer cache={createCache()}>
          <Demo />
        </StyleProvider>,
      );
+     styles.push(...Array.from(document.head.querySelectorAll('style')));
+   }

-   const styles = Array.from(document.head.querySelectorAll('style'));
    expect(styles[0].innerHTML.trim()).toEqual('');
+   // 验证多次注册不会产生重复的空样式元素
+   expect(styles).toHaveLength(1);
  });
src/hooks/useStyleRegister.tsx (2)

336-340: 修复实现简洁有效

通过添加 if (styleStr) 条件检查,确保只有在存在样式内容时才会应用 @layer 包装,这个修复:

  1. 解决了 #51867 中报告的重复 @layer 问题
  2. 实现简单且不影响现有功能
  3. 符合 CSS 规范的最佳实践

建议添加更详细的注释说明这个修复的必要性:

-    // fixme: https://github.com/thysultan/stylis/pull/339
+    // 只在存在样式内容时才添加 @layer 包装
+    // 这个检查解决了当样式内容为空时产生重复 @layer 声明的问题
+    // 相关问题: https://github.com/ant-design/ant-design/issues/51867
+    // Stylis 修复: https://github.com/thysultan/stylis/pull/339
     if (styleStr) {
       styleStr = `@layer ${layer.name} {${styleStr}}`;
     }

336-340: 建议添加性能优化

当前实现在每次解析样式时都会进行字符串拼接,建议通过缓存优化性能:

+    // 使用 Set 缓存已处理的 layer 名称,避免重复处理
+    const processedLayers = new Set<string>();
+
     if (styleStr) {
+      const layerKey = `${layer.name}:${styleStr}`;
+      if (!processedLayers.has(layerKey)) {
         styleStr = `@layer ${layer.name} {${styleStr}}`;
+        processedLayers.add(layerKey);
+      }
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4beb19f and cfe8309.

📒 Files selected for processing (2)
  • src/hooks/useStyleRegister.tsx (1 hunks)
  • tests/layer.spec.tsx (1 hunks)
🔇 Additional comments (1)
tests/layer.spec.tsx (1)

70-72: TODO 注释提供了有价值的上下文信息

这个 TODO 注释很好地引用了相关的 Stylis PR 和 Ant Design issue,帮助理解这个测试用例的背景。建议保留这个注释直到 Stylis 的修复被合并。

@zombieJ zombieJ merged commit b67bf66 into ant-design:master Dec 4, 2024
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.

extraStyle with layer result in duplicated "@layer antd" for table style
2 participants