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(getNow): improve the current time acquisition method #878

Merged
merged 6 commits into from
Sep 24, 2024

Conversation

Wxh16144
Copy link
Contributor

@Wxh16144 Wxh16144 commented Sep 24, 2024

背景

see: ant-design/ant-design#50934

解决方案

优先判断 dayjs 是否存在 dayjs.tz ,如果有且是一个函数,表明用户添加了 dayjs 的 timezone 插件。

当前 PR 改进获取当前时间时,优先使用 dayjs.tz() 获取,其次用默认的 dayjs()

Summary by CodeRabbit

  • 新功能

    • 增强了 getNow 方法,支持时区功能。
    • 引入了新的 TypeScript 声明文件 typings.d.ts,以支持 dayjs 的时区插件。
    • 新增了对 moment-timezone 的依赖,以扩展时区操作的功能。
  • 测试

    • 新增了针对 dayjsGenerateConfig 模块的单元测试,重点测试时区功能。
  • 配置

    • 更新了 tsconfig.json 文件,包含新的类型声明文件路径。

Copy link

vercel bot commented Sep 24, 2024

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

Name Status Preview Comments Updated (UTC)
picker ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 24, 2024 3:16am

Copy link

coderabbitai bot commented Sep 24, 2024

Warning

Rate limit exceeded

@Wxh16144 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 21 minutes and 28 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.

Commits

Files that changed from the base of the PR and between 7930087 and 2f31f29.

Walkthrough

此次更改涉及对 dayjs 库的 getNow 方法进行了修改,以支持时区功能。更新后的实现会检查 dayjs.tz 函数是否可用,并在可用时使用它获取当前时间。此外,新增了单元测试文件以验证时区功能,并引入了一个 TypeScript 声明文件来增强类型定义,同时更新了 tsconfig.json 以包含该声明文件。

Changes

文件 更改摘要
src/generate/dayjs.ts 修改 getNow 方法以支持时区,增加条件检查 dayjs.tz 的可用性。
tests/generateWithTZ.spec.tsx 新增单元测试,验证 dayjsGenerateConfig 的时区功能。
tsconfig.json include 数组中添加 typings.d.ts 文件路径。
typings.d.ts 新增 TypeScript 声明文件,导入 dayjs 的时区插件。
package.json 新增依赖 "moment-timezone": "^0.5.45"

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant dayjsGenerateConfig
    participant dayjs

    User->>dayjsGenerateConfig: 调用 getNow()
    dayjsGenerateConfig->>dayjs: 检查 dayjs.tz 是否可用
    alt dayjs.tz 可用
        dayjsGenerateConfig->>dayjs: 调用 dayjs.tz()
    else dayjs.tz 不可用
        dayjsGenerateConfig->>dayjs: 调用 dayjs()
    end
    dayjs-->>dayjsGenerateConfig: 返回当前时间
    dayjsGenerateConfig-->>User: 返回当前时间
Loading

Poem

🐰 在时区的舞蹈中,
时间跳跃如风,
兔子欢呼着,
日月共舞,
让每一刻都不同!
🌍✨


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

@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

Outside diff range and nitpick comments (4)
tests/generateWithTZ.spec.tsx (2)

14-21: 测试设置和清理看起来不错,但可以稍作改进。

beforeEachafterEach 钩子正确地设置和清理了测试环境,这对于时间相关的测试非常重要。使用 MockDate 模拟特定日期和时间是一个很好的做法。

建议在 afterEach 中也重置 MockDate,以确保完全清理测试环境:

 afterEach(() => {
   dayjs.tz.setDefault();
   MockDate.reset();
+  jest.clearAllMocks();
 });

这样可以确保所有的模拟都被重置,防止测试之间的潜在干扰。


23-37: 测试用例覆盖了重要场景,但可以进行一些改进。

测试用例很好地覆盖了 getNow 函数的正常功能和时区功能。断言看起来正确且全面。

建议进行以下改进:

  1. 将 'should be work' 测试用例的名称改为更具描述性的名称,例如 'should handle different timezones correctly'。

  2. 在 'normal' 测试中,可以直接使用 dayjsGenerateConfig.getNow() 进行测试,而不是使用 new Date(),以确保直接测试目标函数。

  3. 考虑添加更多的边缘情况测试,例如跨日期边界的时区变化。

示例改进:

-it('should be work', async () => {
+it('should handle different timezones correctly', () => {
   dayjs.tz.setDefault(JP);
   const now = dayjsGenerateConfig.getNow();
   const L_now = dayjs();
   expect(L_now.format()).toEqual('2024-09-23T05:02:03+08:00');
   expect(now.format()).toEqual('2024-09-23T06:02:03+09:00');
 });

这些改进将使测试更加清晰和全面。

src/generate/dayjs.ts (2)

110-116: 代码变更看起来不错,建议小幅改进

这个改动很好地增强了对时区的支持,同时保持了向后兼容性。代码逻辑清晰,并且添加了有用的注释来解释变更的原因。

为了进一步提高代码的可读性和可维护性,我建议将检查逻辑提取到一个单独的函数中。这样可以使主函数更简洁,并且更容易在将来进行修改。例如:

+const hasTzSupport = () => typeof dayjs.tz === 'function';
+
 getNow: () => {
-  if (typeof dayjs.tz === 'function') {
+  if (hasTzSupport()) {
     // https://github.com/ant-design/ant-design/discussions/50934
     return dayjs.tz();
   }
   return dayjs();
 },

这个小改动可以使代码更加模块化,并且更容易理解和维护。


建议在 src/generate/dayjs.ts 中导入和初始化时区插件

当前的改动增加了对 dayjs.tz 的支持,但在 src/generate/dayjs.ts 文件中未发现时区插件的导入和初始化。为了确保新功能正常工作,建议进行以下操作:

  1. 在文件顶部导入时区插件和 UTC 插件:

    import timezone from 'dayjs/plugin/timezone';
    import utc from 'dayjs/plugin/utc';
  2. 在文件中初始化这些插件:

    dayjs.extend(utc);
    dayjs.extend(timezone);
  3. 验证这些更改不会影响项目的其他部分。

Analysis chain

Line range hint 1-7: 建议验证时区插件的导入和初始化

当前的改动增加了对 dayjs.tz 的支持,但我没有看到时区插件的导入。为了确保新功能正常工作,建议进行以下操作:

  1. 确保在文件顶部导入了时区插件:

    import timezone from 'dayjs/plugin/timezone';
    import utc from 'dayjs/plugin/utc';
  2. 在文件中初始化这些插件:

    dayjs.extend(utc);
    dayjs.extend(timezone);
  3. 验证这些更改不会影响项目的其他部分。

可以运行以下脚本来检查是否已经在项目中的某处导入了这些插件:

如果这些导入和初始化已经在项目的其他地方完成,那么当前的改动就是正确的。否则,建议在适当的位置添加必要的导入和初始化代码。

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
echo "Searching for dayjs timezone plugin import..."
rg --type typescript "import.*dayjs/plugin/(timezone|utc)"

echo "\nSearching for dayjs timezone plugin initialization..."
rg --type typescript "dayjs\.extend\((timezone|utc)\)"

Length of output: 409


Script:

#!/bin/bash
echo "Searching for dayjs timezone plugin import in .ts and .tsx files..."
rg "import\s+.*dayjs/plugin/(timezone|utc)" --glob "*.ts" --glob "*.tsx"

echo "\nSearching for dayjs timezone plugin initialization in .ts and .tsx files..."
rg "dayjs\.extend\((timezone|utc)\)" --glob "*.ts" --glob "*.tsx"

Length of output: 742

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7689208 and cfa83ea.

Files selected for processing (4)
  • src/generate/dayjs.ts (1 hunks)
  • tests/generateWithTZ.spec.tsx (1 hunks)
  • tsconfig.json (1 hunks)
  • typings.d.ts (1 hunks)
Additional context used
Biome
typings.d.ts

[error] 2-3: This empty export is useless because there's another export or import.

This import makes useless the empty export.

Safe fix: Remove this useless empty export.

(lint/complexity/noUselessEmptyExport)

Additional comments not posted (4)
typings.d.ts (1)

1-1: 导入 dayjs 时区插件正确。

导入 dayjs 的时区插件是正确的,这将允许在项目中使用 dayjs 的时区功能。

tsconfig.json (1)

22-23: 添加了 typings.d.ts 文件到编译范围内,这是一个良好的做法。

通过将 "typings.d.ts" 添加到 include 数组中,您确保了 TypeScript 编译器会考虑这个文件中的自定义类型定义。这有助于增强项目的类型检查和代码补全功能,特别是对于那些没有内置类型定义的第三方库或自定义全局类型。

tests/generateWithTZ.spec.tsx (2)

1-12: 导入和设置看起来很好!

导入必要的模块和插件,并正确设置了 Day.js 的 UTC 和时区功能。使用常量来定义时区字符串是一个很好的做法,提高了代码的可读性和可维护性。


1-37: 总体评价:测试文件结构良好,覆盖了重要场景

这个测试文件为 dayjsGenerateConfig 模块提供了良好的单元测试,特别是针对 Day.js 库的时区功能。测试设置、清理和用例结构都很合理。建议的改进主要集中在提高测试的清晰度和全面性,包括更具描述性的测试名称和考虑更多边缘情况。

实施这些小改进后,这个测试文件将为 getNow 函数提供更强大和可靠的测试覆盖。

@@ -0,0 +1,3 @@
import 'dayjs/plugin/timezone';

export {};
Copy link

Choose a reason for hiding this comment

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

建议移除空的导出语句。

空的导出语句在这里是不必要的,因为文件已经有了一个导入语句。移除它可以使代码更简洁。

建议应用以下更改:

import 'dayjs/plugin/timezone';

- export {};
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export {};
import 'dayjs/plugin/timezone';
Tools
Biome

[error] 2-3: This empty export is useless because there's another export or import.

This import makes useless the empty export.

Safe fix: Remove this useless empty export.

(lint/complexity/noUselessEmptyExport)

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 (1)
package.json (1)

78-78: 新增 moment-timezone 依赖

添加 moment-timezone 依赖是一个好的改进,可以增强时区处理能力。然而,有几点建议:

  1. 考虑将 moment 也移到直接依赖中,因为 moment-timezone 通常与 moment 一起使用。

  2. 项目中似乎使用了多个日期库(dayjs, luxon, date-fns)。建议检查是否真的需要 moment-timezone,或者是否可以统一使用一个日期库来处理所有时间相关的操作,以减少依赖并提高一致性。

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between cfa83ea and 1d6b65a.

Files selected for processing (2)
  • package.json (1 hunks)
  • tests/generateWithTZ.spec.tsx (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • tests/generateWithTZ.spec.tsx

@afc163
Copy link
Member

afc163 commented Sep 24, 2024

看一下测试用例

@Wxh16144
Copy link
Contributor Author

很奇怪,写这个测试用例仿佛进入了自证陷阱...

@Wxh16144 Wxh16144 changed the title feat(getNow): Improve the current time acquisition method Draft feat(getNow): Improve the current time acquisition method Sep 24, 2024
Copy link

codecov bot commented Sep 24, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.43%. Comparing base (7689208) to head (2f31f29).
Report is 1 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #878   +/-   ##
=======================================
  Coverage   95.42%   95.43%           
=======================================
  Files          64       64           
  Lines        2712     2716    +4     
  Branches      731      732    +1     
=======================================
+ Hits         2588     2592    +4     
  Misses        121      121           
  Partials        3        3           

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

@Wxh16144 Wxh16144 changed the title Draft feat(getNow): Improve the current time acquisition method feat(getNow): improve the current time acquisition method Sep 24, 2024
@Wxh16144
Copy link
Contributor Author

ready~ 🎉

Comment on lines +110 to +117
getNow: () => {
const now = dayjs();
// https://github.com/ant-design/ant-design/discussions/50934
if (typeof now.tz === 'function') {
return now.tz(); // use default timezone
}
return now;
},
Copy link
Contributor Author

Choose a reason for hiding this comment

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

dayjs.tz 是原型上的方法: ref:https://github.com/iamkun/dayjs/blob/fa1612328b4e2dc0263f5b7e83eeeb343ccd7021/src/plugin/timezone/index.js#L95

dayjs().tz 是 Dayjs 对象上的方法:https://github.com/iamkun/dayjs/blob/fa1612328b4e2dc0263f5b7e83eeeb343ccd7021/src/plugin/timezone/index.js#L135
dayjs().tz 是转换到对应时区,不填时,转化到 setDefault 设置的默认时区

以上纯个人看文档理解的,有错误欢迎指出

Copy link
Member

Choose a reason for hiding this comment

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

担心 getNow 不太够,怕有什么地方被穿掉,但是试了一下似乎没问题~

@afc163 afc163 merged commit df3e060 into react-component:master Sep 24, 2024
9 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.

3 participants