Skip to content

refactor: use props check instead of version check #593

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

Merged
merged 4 commits into from
Dec 5, 2024
Merged

Conversation

zombieJ
Copy link
Member

@zombieJ zombieJ commented Dec 5, 2024

replaced with MUI resolution. It's more flexible:

https://github.com/mui/material-ui/blob/master/packages/mui-utils/src/getReactNodeRef/getReactNodeRef.ts

Summary by CodeRabbit

  • 新特性

    • 更新了项目依赖,支持 React 19 和 React DOM 19 的新版本。
  • 测试

    • getNodeRef 函数添加了针对 React 19 的测试套件,确保功能正常并监控控制台错误。
    • 在现有测试中引入了控制台错误监视器,以验证测试执行期间没有错误被记录。

Copy link

vercel bot commented Dec 5, 2024

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

Name Status Preview Comments Updated (UTC)
util ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 5, 2024 11:29am

Copy link

coderabbitai bot commented Dec 5, 2024

Warning

Rate limit exceeded

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

Reviewing files that changed from the base of the PR and between 2061d7f and ce78edf.

Walkthrough

本次更改涉及多个文件的更新,主要包括在 package.json 中添加了对 React 19 和 React DOM 19 的新依赖。此外,src/ref.ts 中的 getNodeRef 函数进行了简化,移除了对 React 版本的条件检查,改为统一的逻辑以提高可读性和可维护性。最后,新增了针对 React 19 的测试文件 tests/ref-19.test.tsx,并在现有的 tests/ref.test.tsx 中添加了控制台错误监视器,以确保测试期间没有错误日志。

Changes

文件路径 更改摘要
package.json 添加新依赖:"react-19": "npm:react@19.0.0-rc-de68d2f4-20241204""react-dom-19": "npm:react-dom@19.0.0-rc-de68d2f4-20241204";更新 reactreact-dom 的对等依赖。
src/ref.ts 更新 getNodeRef 函数,简化实现,移除版本检查,使用统一逻辑获取 ref 属性。
tests/ref-19.test.tsx 新增测试套件,针对 React 19 的 getNodeRef 函数进行测试,确保兼容性和正确性。
tests/ref.test.tsx 添加控制台错误监视器,确保测试期间没有错误日志。

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

codecov bot commented Dec 5, 2024

Codecov Report

Attention: Patch coverage is 80.00000% with 1 line in your changes missing coverage. Please review.

Project coverage is 89.84%. Comparing base (7aaa1d8) to head (ce78edf).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
src/ref.ts 80.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #593      +/-   ##
==========================================
+ Coverage   89.47%   89.84%   +0.36%     
==========================================
  Files          40       40              
  Lines         979      975       -4     
  Branches      328      325       -3     
==========================================
  Hits          876      876              
+ Misses        100       96       -4     
  Partials        3        3              

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

Copy link

socket-security bot commented Dec 5, 2024

New and removed dependencies detected. Learn more about Socket for GitHub ↗︎

Package New capabilities Transitives Size Publisher
npm/react-dom@19.0.0-rc-de68d2f4-20241204 None +1 6.62 MB fb, gnoff, react-bot, ...2 more

View full report↗︎

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: 2

🧹 Outside diff range and nitpick comments (3)
src/ref.ts (1)

88-90: 建议添加实现说明注释

虽然添加了源代码链接,但建议补充说明这种实现方式的原理和优势,以便其他开发者理解。

🧰 Tools
🪛 Biome (1.9.4)

[error] 90-90: Do not access Object.prototype method 'propertyIsEnumerable' from target object.

(lint/suspicious/noPrototypeBuiltins)

tests/ref-19.test.tsx (1)

5-13: 建议优化 mock 实现

当前的 mock 实现可能会在测试环境中造成一些副作用。建议:

  1. afterAll 中清理 mock
  2. 确保只 mock 必要的方法而不是整个模块
tests/ref.test.tsx (1)

216-217: 建议增强错误监控的测试覆盖率

虽然基本的错误监控已经实现,但建议添加以下改进:

  1. 添加正向测试用例,验证在预期的错误情况下确实触发了 console.error
  2. 为不同的 props 场景添加专门的测试用例,确保 props 检查的准确性

建议参考以下示例添加测试用例:

it('should log error for invalid props', () => {
  const invalidNode = <div prop={null} />;
  getNodeRef(invalidNode);
  expect(errSpy).toHaveBeenCalled();
});

it('should handle different prop scenarios', () => {
  const validNode = <div ref={React.createRef()} />;
  getNodeRef(validNode);
  expect(errSpy).not.toHaveBeenCalled();
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7aaa1d8 and 4c15657.

📒 Files selected for processing (4)
  • package.json (1 hunks)
  • src/ref.ts (1 hunks)
  • tests/ref-19.test.tsx (1 hunks)
  • tests/ref.test.tsx (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/ref.ts

[error] 90-90: Do not access Object.prototype method 'propertyIsEnumerable' from target object.

(lint/suspicious/noPrototypeBuiltins)

🪛 GitHub Check: codecov/patch
src/ref.ts

[warning] 92-92: src/ref.ts#L92
Added line #L92 was not covered by tests

🔇 Additional comments (2)
package.json (1)

70-71: 验证 React 19 RC 版本的稳定性

新增的 React 19 RC 版本依赖使用了特定的提交哈希值,这对测试来说是好的做法。但是需要注意:

  • RC 版本可能存在不稳定性
  • 后续需要及时更新到正式发布版本
tests/ref.test.tsx (1)

15-19: 控制台错误监控设置正确!

错误监控的实现遵循了 Jest 的最佳实践,通过 beforeEach 确保每个测试用例都有一个干净的监控状态。

Comment on lines +84 to +93
) => React.Ref<T> | null = node => {
if (node && isReactElement(node)) {
const ele = node as any;

// Source from:
// https://github.com/mui/material-ui/blob/master/packages/mui-utils/src/getReactNodeRef/getReactNodeRef.ts
return ele.props.propertyIsEnumerable('ref') ? ele.props.ref : ele.ref;
}
return null;
};
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

建议优化 ref 获取逻辑的实现

当前实现存在以下问题:

  1. 直接调用目标对象的 propertyIsEnumerable 方法可能不安全
  2. 新增的返回 null 分支缺少测试覆盖

建议进行如下优化:

export const getNodeRef: <T = any>(
  node: React.ReactNode,
) => React.Ref<T> | null = node => {
  if (node && isReactElement(node)) {
    const ele = node as any;
-   return ele.props.propertyIsEnumerable('ref') ? ele.props.ref : ele.ref;
+   return Object.prototype.propertyIsEnumerable.call(ele.props, 'ref') 
+     ? ele.props.ref 
+     : ele.ref;
  }
  return null;
};
📝 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
) => React.Ref<T> | null = node => {
if (node && isReactElement(node)) {
const ele = node as any;
// Source from:
// https://github.com/mui/material-ui/blob/master/packages/mui-utils/src/getReactNodeRef/getReactNodeRef.ts
return ele.props.propertyIsEnumerable('ref') ? ele.props.ref : ele.ref;
}
return null;
};
) => React.Ref<T> | null = node => {
if (node && isReactElement(node)) {
const ele = node as any;
// Source from:
// https://github.com/mui/material-ui/blob/master/packages/mui-utils/src/getReactNodeRef/getReactNodeRef.ts
return Object.prototype.propertyIsEnumerable.call(ele.props, 'ref')
? ele.props.ref
: ele.ref;
}
return null;
};
🧰 Tools
🪛 Biome (1.9.4)

[error] 90-90: Do not access Object.prototype method 'propertyIsEnumerable' from target object.

(lint/suspicious/noPrototypeBuiltins)

🪛 GitHub Check: codecov/patch

[warning] 92-92: src/ref.ts#L92
Added line #L92 was not covered by tests

Comment on lines +22 to +29
it('getNodeRef', () => {
const ref = React.createRef<HTMLDivElement>();
const node = <div ref={ref} />;

expect(getNodeRef(node)).toBe(ref);

expect(errSpy).not.toHaveBeenCalled();
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

建议增加更多测试用例

当前测试只覆盖了基本场景,建议添加以下测试用例:

  1. 传入 null/undefined 节点的情况
  2. 传入非 React 元素的情况
  3. 不同类型的 ref(函数式、对象式)

示例测试用例:

it('should handle null/undefined', () => {
  expect(getNodeRef(null)).toBe(null);
  expect(getNodeRef(undefined)).toBe(null);
});

it('should handle non-React elements', () => {
  expect(getNodeRef('string')).toBe(null);
  expect(getNodeRef(123)).toBe(null);
});

it('should work with function ref', () => {
  const fnRef = jest.fn();
  const node = <div ref={fnRef} />;
  expect(getNodeRef(node)).toBe(fnRef);
});

@zombieJ zombieJ merged commit bf1dc6a into master Dec 5, 2024
11 of 12 checks passed
@zombieJ zombieJ deleted the getRef branch January 16, 2025 08:58
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