Skip to content

Remove findDOMNode from rc-mutate-observer #14

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
Jan 24, 2025

Conversation

Roxannej
Copy link
Contributor

@Roxannej Roxannej commented Jan 14, 2025

Summary by CodeRabbit

  • 新功能

    • useMutateObserver 函数现在支持处理 SVG 元素。
  • 测试改进

    • 更新了 MutateObserver 组件的测试用例
    • 优化测试中的错误处理和事件模拟
    • 添加了对控制台错误的监控机制
  • 代码重构

    • 简化了目标元素的设置逻辑
    • 移除了对 findDOMNode 的依赖
    • 优化了 useLayoutEffect 钩子的实现
    • 删除了 DomWrapper 组件

Copy link

coderabbitai bot commented Jan 14, 2025

概述

代码走查

本次更改主要涉及 MutateObserver.tsxtests/index.test.tsxuseMutateObserver.tsxwrapper.ts 四个文件。在 MutateObserver.tsx 中,开发者重构了目标元素的设置逻辑,移除了 findDOMNode 的使用,并优化了 useLayoutEffect 钩子。tests/index.test.tsx 更新了测试用例,增加了对错误处理和 React.StrictMode 的测试覆盖。useMutateObserver.tsx 的参数类型被扩展以支持 SVG 元素,而 wrapper.ts 文件则被删除。

变更

文件 变更摘要
src/MutateObserver.tsx - 移除 findDOMNode 导入
- 重新排序导入语句
- 更新 elementReftarget 的类型
- 简化引用处理逻辑
- 修改 useLayoutEffect 中的目标元素设置逻辑
- 移除 DomWrapper 的渲染逻辑
tests/index.test.tsx - 添加 useMutateObserver 的模拟实现
- 更新测试用例注释
- 添加 console.error 模拟
- 增加对 nativeElement 属性的测试
src/useMutateObserver.tsx - 更新 nodeOrList 参数的类型,支持 SVG 元素
src/wrapper.ts - 删除 DomWrapper 组件

诗歌

🐰 代码如流水,变化无痕
重构的魔法,性能飞翔
测试严谨如丝,无错无伤
兔子微笑,代码长青
技术之美,尽在掌中 🚀


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

🧹 Nitpick comments (4)
src/MutateObserver.tsx (2)

31-37: 优化目标元素的设置逻辑

新的实现成功移除了 findDOMNode,代码更加清晰。不过,我们可以通过缓存 canRef 的计算结果来进一步优化性能。

建议如下优化:

- const canRef = React.isValidElement(children) && supportRef(children);
+ const canRef = React.useMemo(
+   () => React.isValidElement(children) && supportRef(children),
+   [children]
+ );

Line range hint 41-44: 改进错误消息的可读性

当前的错误消息可以更加具体,以帮助开发者更快地定位问题。

建议如下修改:

- console.error('MutationObserver need children props');
+ console.error('MutationObserver requires children prop to be provided. Received: null');
tests/index.test.tsx (2)

39-41: 建议改进测试清理逻辑

虽然在测试结束时恢复了 console.error,但建议使用 afterEach 来确保在测试失败时也能正确清理。

+ beforeEach(() => {
+   jest.spyOn(console, 'error').mockImplementation(() => {});
+ });
+ 
+ afterEach(() => {
+   jest.restoreAllMocks();
+ });
+ 
  it('MutateObserver should work without errors in React.StrictMode', () => {
    const fn = jest.fn();
    const buttonRef = React.createRef<HTMLButtonElement>();
-   
-   // Mock console.error to ensure no warnings are logged
-   const warnSpy = jest.spyOn(console, 'error').mockImplementation(() => {});

65-70: 建议增加更具体的断言

当前的断言验证了没有警告,但可以添加更多断言来验证组件的具体行为。

建议添加以下断言:

// 验证按钮类名的变化
expect(container.querySelector('button')).toHaveClass('bbb');

// 验证回调函数的参数
if ('MutationObserver' in window) {
  expect(fn).toHaveBeenCalledWith(
    expect.arrayContaining([
      expect.objectContaining({
        type: 'attributes',
        attributeName: 'class'
      })
    ])
  );
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e0403d2 and b4d524b.

📒 Files selected for processing (2)
  • src/MutateObserver.tsx (2 hunks)
  • tests/index.test.tsx (4 hunks)
🔇 Additional comments (2)
src/MutateObserver.tsx (1)

1-7: 导入语句的重组看起来不错!

导入语句的重组提高了代码的可读性,同时成功移除了 findDOMNode 的依赖。

tests/index.test.tsx (1)

Line range hint 23-30: 测试用例的改进很棒!

添加的注释和浏览器兼容性检查提高了测试的可读性和可靠性。

@li-jia-nan
Copy link
Member

@Roxannej 冲突了

@zombieJ zombieJ changed the title Remove findDOMNode from rc-css-motion Remove findDOMNode from rc-mutate-observer Jan 24, 2025
Copy link

codecov bot commented Jan 24, 2025

Codecov Report

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

Project coverage is 78.78%. Comparing base (58192dd) to head (84330d1).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
src/MutateObserver.tsx 88.88% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master      #14      +/-   ##
==========================================
- Coverage   78.94%   78.78%   -0.16%     
==========================================
  Files           3        2       -1     
  Lines          38       33       -5     
  Branches       13       11       -2     
==========================================
- Hits           30       26       -4     
  Misses          7        7              
+ Partials        1        0       -1     

☔ 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

🧹 Nitpick comments (2)
src/MutateObserver.tsx (2)

18-24: 建议增强类型安全性

当前实现已经很好地支持了 HTML 和 SVG 元素,但我们可以进一步改进类型定义。

建议添加以下类型定义来增强代码的可维护性:

+type SupportedElement = HTMLElement | SVGElement;
-const elementRef = React.useRef<HTMLElement | SVGElement>(null);
+const elementRef = React.useRef<SupportedElement>(null);
-const [target, setTarget] = React.useState<HTMLElement | SVGElement>(null);
+const [target, setTarget] = React.useState<SupportedElement>(null);

30-34: 建议添加错误处理

当前的实现可能在某些边缘情况下不够健壮。

建议添加错误处理和日志记录:

 if (canRef && elementRef.current) {
-  setTarget(getDOM(elementRef.current));
+  try {
+    const domNode = getDOM(elementRef.current);
+    if (!domNode && process.env.NODE_ENV !== 'production') {
+      console.warn('无法获取目标 DOM 节点');
+    }
+    setTarget(domNode);
+  } catch (error) {
+    if (process.env.NODE_ENV !== 'production') {
+      console.error('获取 DOM 节点时发生错误:', error);
+    }
+  }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d3bc0b2 and 84330d1.

📒 Files selected for processing (1)
  • src/MutateObserver.tsx (3 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
src/MutateObserver.tsx

[warning] 46-46: src/MutateObserver.tsx#L46
Added line #L46 was not covered by tests

🔇 Additional comments (2)
src/MutateObserver.tsx (2)

1-9: 导入更改看起来不错!

导入更改符合 React 最佳实践,通过使用 getDOM 替换已弃用的 findDOMNode


44-46: 需要增加测试覆盖率

静态分析显示第 46 行缺少测试覆盖。

建议添加以下测试场景:

  1. canReffalse 时的渲染情况
  2. 确保 children 在不支持 ref 时保持不变

需要我帮您生成相应的测试用例吗?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 46-46: src/MutateObserver.tsx#L46
Added line #L46 was not covered by tests

@zombieJ zombieJ merged commit ade7799 into react-component:master Jan 24, 2025
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.

3 participants