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

feat: Progress bar with customizable colors #363

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

yellowryan
Copy link

@yellowryan yellowryan commented Jan 26, 2025

New feature for #52268

Summary by CodeRabbit

  • 新功能

    • 为通知组件添加了自定义进度条颜色的功能
    • 支持设置纯色和渐变色的进度条颜色
  • 测试

    • 新增测试用例验证自定义进度条颜色功能
  • 样式

    • 引入新的CSS变量 --progress-color 以控制进度条颜色
    • 提高样式的灵活性和可定制性

Copy link

vercel bot commented Jan 26, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
notification ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 26, 2025 11:30pm

Copy link

coderabbitai bot commented Jan 26, 2025

概述

演练

这个更改引入了通知组件进度条颜色的自定义功能。通过添加一个新的可选属性 progressBarColor,开发者现在可以为通知的进度条指定自定义颜色。这个特性涉及多个文件的修改,包括样式表、组件定义、接口和测试用例,以支持这一新的灵活性。

变更

文件 变更摘要
assets/index.less 引入 --progress-color CSS 变量,替换硬编码的进度条颜色
src/Notice.tsx 添加 progressBarColor 属性,支持进度条颜色自定义
src/hooks/useNotification.tsx NotificationConfig 接口中新增 progressBarColor 可选属性
src/interface.ts NoticeConfig 接口中新增 progressBarColor 可选属性
docs/examples/showProgress.tsx 添加演示自定义进度条颜色的按钮示例
tests/index.test.tsx 新增测试用例验证自定义进度条颜色功能

序列图

sequenceDiagram
    participant User
    participant Notification
    participant NoticeComponent
    participant StyleSystem

    User->>Notification: 调用通知并设置progressBarColor
    Notification->>NoticeComponent: 传递颜色参数
    NoticeComponent->>StyleSystem: 应用CSS变量
    StyleSystem-->>NoticeComponent: 渲染带有自定义颜色的进度条
Loading

诗歌

🐰 兔子的进度条魔法
颜色随心变,灵活如流光
红黄蓝绿舞,通知有乾坤
代码中的彩虹,闪耀不停歇!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

@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 (6)
docs/examples/showProgress.tsx (1)

31-40: 建议改进示例代码的展示方式

示例代码可以更全面地展示 progressBarColor 的使用方式:

  • 展示多种颜色格式(HEX、RGB、HSL等)
  • 添加更多示例按钮以展示不同颜色效果
  • 使用更具语义化的颜色值
       <button
         onClick={() => {
           notice.open({
             content: `${new Date().toISOString()}`,
-            progressBarColor: 'yellow',
+            progressBarColor: '#1890ff',
           });
         }}
       >
-        Show Progress Bar with custom color
+        Show Blue Progress Bar
       </button>
+      <button
+        onClick={() => {
+          notice.open({
+            content: `${new Date().toISOString()}`,
+            progressBarColor: 'rgb(82, 196, 26)',
+          });
+        }}
+      >
+        Show Green Progress Bar
+      </button>
src/interface.ts (1)

11-11: 建议改进类型定义和文档

progressBarColor 的类型定义可以更严格和清晰:

  • 添加 JSDoc 文档说明支持的颜色格式
  • 考虑使用更严格的类型定义来限制有效的颜色值
-  progressBarColor?: string;
+  /** 
+   * 进度条颜色。支持以下格式:
+   * - 关键字颜色名称:'blue', 'red' 等
+   * - HEX 格式:'#1890ff'
+   * - RGB 格式:'rgb(24, 144, 255)'
+   * - HSL 格式:'hsl(215, 100%, 50%)'
+   */
+  progressBarColor?: React.CSSProperties['color'];
src/Notice.tsx (2)

44-44: 建议添加颜色值验证

建议添加颜色值验证逻辑,以防止无效的颜色值导致样式问题。

+  const isValidColor = (color: string) => {
+    const s = new Option().style;
+    s.color = color;
+    return s.color !== '';
+  };
+
-  const mergedProgressBarColor = mergedShowProgress && progressBarColor;
+  const mergedProgressBarColor = mergedShowProgress && progressBarColor && 
+    isValidColor(progressBarColor) ? progressBarColor : undefined;

173-178: 建议优化无障碍性能

为进度条添加 ARIA 属性以提升无障碍性能。

   <progress
     ref={progressRef}
     className={`${noticePrefixCls}-progress`}
     max="100"
     value={validPercent}
+    role="progressbar"
+    aria-valuemin="0"
+    aria-valuemax="100"
+    aria-valuenow={validPercent}
   >
assets/index.less (1)

107-107: CSS 变量实现进度条颜色自定义

使用 CSS 自定义属性实现进度条颜色的动态配置是一个很好的方案。建议考虑以下优化:

  1. 为颜色变量添加 fallback 值以提高兼容性
  2. 考虑添加浏览器前缀以支持更多浏览器
-  --progress-color: #31afff;
+  --progress-color: var(--progress-color, #31afff);

Also applies to: 115-115, 119-119

tests/index.test.tsx (1)

853-891: 测试用例完整性良好

测试用例覆盖了以下关键场景:

  1. 自定义纯色进度条
  2. 渐变色进度条

建议添加以下测试场景:

  1. 无效颜色值的处理
  2. 动态更新颜色的情况
  3. 浏览器兼容性边缘情况
it('should handle invalid color values gracefully', () => {
  const { instance } = renderDemo({
    duration: 1,
    showProgress: true,
    progressBarColor: 'invalid-color',
  });

  act(() => {
    instance.open({
      content: <p className="test">1</p>,
    });
  });

  expect(document.querySelector('.rc-notification-notice-progress')).toHaveStyle({
    '--progress-color': 'invalid-color',
  });
});

it('should update progress bar color dynamically', () => {
  const { instance } = renderDemo({
    duration: 1,
    showProgress: true,
    progressBarColor: 'red',
  });

  act(() => {
    instance.open({
      content: <p className="test">1</p>,
      progressBarColor: 'blue',
    });
  });

  expect(document.querySelector('.rc-notification-notice-progress')).toHaveStyle({
    '--progress-color': 'blue',
  });
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0a6f542 and e6441e9.

📒 Files selected for processing (6)
  • assets/index.less (1 hunks)
  • docs/examples/showProgress.tsx (1 hunks)
  • src/Notice.tsx (4 hunks)
  • src/hooks/useNotification.tsx (1 hunks)
  • src/interface.ts (1 hunks)
  • tests/index.test.tsx (1 hunks)
🔇 Additional comments (1)
src/hooks/useNotification.tsx (1)

21-21: 代码变更正确且符合预期

progressBarColor 属性的添加符合接口设计规范,且不影响现有功能。

Comment on lines +107 to +111
React.useEffect(() => {
if (mergedProgressBarColor) {
progressRef.current!.style.setProperty('--progress-color', mergedProgressBarColor);
}
}, [mergedProgressBarColor]);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

建议优化 useEffect 的实现方式

当前实现存在以下问题:

  1. 直接操作 DOM 不符合 React 最佳实践
  2. 可能存在内存泄漏风险

建议使用 React 的 style 属性来设置颜色:

-  React.useEffect(() => {
-    if (mergedProgressBarColor) {
-      progressRef.current!.style.setProperty('--progress-color', mergedProgressBarColor);
-    }
-  }, [mergedProgressBarColor]);

   // 在 progress 元素上直接使用 style
   <progress
-    ref={progressRef}
     className={`${noticePrefixCls}-progress`}
+    style={{ '--progress-color': mergedProgressBarColor }}
     max="100"
     value={validPercent}
   >

Committable suggestion skipped: line range outside the PR's diff.

Copy link

codecov bot commented Jan 27, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 99.74%. Comparing base (0a6f542) to head (e6441e9).

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #363   +/-   ##
=======================================
  Coverage   99.73%   99.74%           
=======================================
  Files           7        7           
  Lines         759      774   +15     
  Branches      123      126    +3     
=======================================
+ Hits          757      772   +15     
  Misses          2        2           

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

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